PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

Similar documents
PHP. Interactive Web Systems

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

What is PHP? [1] Figure 1 [1]

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

PHP by Pearson Education, Inc. All Rights Reserved.

PHP: Hypertext Preprocessor. A tutorial Introduction

CERTIFICATE IN WEB PROGRAMMING

Pace University. Fundamental Concepts of CS121 1

B. V. Patel Institute of BMC & IT 2014

M275 - Web Development using PHP and MySQL

COMP519 Practical 5 JavaScript (1)

PHP INTERVIEW QUESTION-ANSWERS

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2017

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

week8 Tommy MacWilliam week8 October 31, 2011

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 2011

introduction to records in touchdevelop

JavaScript Functions, Objects and Array

A Web-Based Introduction

PHP Introduction. Some info on MySQL which we will cover in the next workshop...

SPARK-PL: Introduction

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Quiz 1 Review Session. November 17th, 2014

Server side basics CS380

Exploring UNIX: Session 3

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 1 INTRODUCTION

CSC105, Introduction to Computer Science I. Introduction. Perl Directions NOTE : It is also a good idea to

PHPoC vs PHP > Overview. Overview

CHIL CSS HTML Integrated Language

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

Options. Real SQL Programming 1. Stored Procedures. Embedded SQL

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

CS112 Lecture: Repetition Statements

CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2016

Full file at

COMPUTER APPLICATION

Web Application Development (WAD) V th Sem BBAITM (Unit 4) By: Binit Patel

PHPoC. PHPoC vs PHP. Version 1.1. Sollae Systems Co., Ttd. PHPoC Forum: Homepage:

C Language Programming

ORB Education Quality Teaching Resources

CS201 - Introduction to Programming Glossary By

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

Lecture 3: Web Servers / PHP and Apache. CS 383 Web Development II Monday, January 29, 2018

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

Working with JavaScript

8. Control statements

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Chapter 2: Functions and Control Structures

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Microsoft Excel Level 2

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Contents. Note: pay attention to where you are. Note: Plaintext version. Note: pay attention to where you are... 1 Note: Plaintext version...

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CHAPTER 2 MARKUP LANGUAGES: XHTML 1.0

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Tutorial 10: Programming with JavaScript

The main differences with other open source reporting solutions such as JasperReports or mondrian are:

Objectives. In this chapter, you will:

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

JME Language Reference Manual

Types, lists & functions

A Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

CSCU9B2 Practical 1: Introduction to HTML 5

CSC Web Programming. Introduction to JavaScript

Short Notes of CS201

Introduction, Notepad++, File Structure, 9 Tags, Hyperlinks 1

Preview from Notesale.co.uk Page 6 of 52

CS 6353 Compiler Construction Project Assignments

Scripting. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

Intro. Scheme Basics. scm> 5 5. scm>

Max and Programming Is Max a Programming Language?

Distributed Databases and Remote Access to a Database

Part III Appendices 165

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Quick.JS Documentation

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

GNU ccscript Scripting Guide IV

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Programming for the Web with PHP

My Favorite bash Tips and Tricks

CS112 Lecture: Loops

Reading How the Web Works

PHP. MIT 6.470, IAP 2010 Yafim Landa

This lecture. PHP tags

Linux Systems Administration Shell Scripting Basics. Mike Jager Network Startup Resource Center

Course Outline. Introduction to java

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

Transcription:

PHP Reference 1 Preface This tutorial is designed to teach you all the PHP commands and constructs you need to complete your PHP project assignment. It is assumed that you have never programmed in PHP before. Although the material focuses just on those elements needed to complete the project, you should also gain a simple understanding of what PHP can do. All of the information in this tutorial comes from the official PHP manual found at http://www.php.net /manual/en/. This is an excellent resource at your disposal. It offers user-contributed examples and further explanations of PHP elements. If you want to learn about those PHP elements not needed to complete the project, or even acquire a greater knowledge of those elements that are referred to here, you will find the manual to be very informative and clear. If you are already familiar with PHP, you will still benefit from this tutorial if you have never used PHP to connect to a MySQL database. You will learn how to connect to a MySQL database, execute queries, traverse through the results, and set the proper permissions so that your scripts will work. 2 Using MySQL You will be using MySQL, as opposed to oracle, for your PHP project assignment. Both are SQL DMBSs, however, they do not share data, so you will need to insert all data pertinent to the PHP project into your MySQL database. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed: bash$ mysql -p This will attempt to log you in using your current username, asking for a password. The next thing you need to do is select a database. At the MySQL prompt, type: mysql> show databases; To list databases available to you. There should be one named after your username. To select it, type mysql> use <my database name>; After that, you can create tables and run queries. To access your MySQL database through the PHP script, follow the directions given in Section 5. 3 Introduction For the PHP project assignment, you will learn to write PHP scripts that connect to your MySQL database and simulate recursive SQL queries. You will also learn to make a Web page that serves as an easy-to-use interface to your PHP scripts. Refer to the project Web page for the detailed project requirements. At this point, you might be asking, Why do we really need PHP? SQL seemed to work just fine for the previous projects. The problem is that although Oracle 8i sqlplus supports hierarchical queries, it does not support true recursion e.g., Find the cheapest airfare from Montreal to SLC.. In Project 2, we avoided this issue by ensuring that i the answers did not include a route with more than one layover, and ii flight routes did not contain any loops. 1

PHP is a powerful, Web-scripting language that can interact with a database and provide the functionality of recursion. It also allows us to perform more computations on the data than we could do with just an SQL engine. 3.1 The power of PHP As a Web-scripting language, some of PHP s greatest strengths lie in its Web development features and its ease of embedding code within HTML. However, it can also be used as a general programming language. Earlier, we have already hinted at PHP s abilities to interact with a databaseindeed, more than 20 different databases are supported. PHP is also known for its ability to generate dynamic page content. Web page content is usually dynamically created by a server and then sent to a client Web browser. This approach is called server-side scripting. Note how this differs from JavaScript, which executes on the client side. The Web browser treats the output of the PHP script just like any other Web page; you cannot see the original PHP code. Even if you try to View Source, you will see just the dynamically generated HTML or text. 3.2 Our approach Technically, our approach is not server-side scripting because the Web server does not actually need to be running for the PHP scripts to work. They can, and should first, be run from the command line. It is much easier to debug a script from the command line, since a Web Browser provides practically no clues as to why an invalid PHP script is not working. Thus, we will use command-line scripting. However, Web access of PHP scripts will still be permitted. A high-level view of the required communication steps are shown below. 1. The Web browser requests your Web interface an HTML file from the Web server on Sources. 2. The Web server retrieves your HTML file and sends it back to the Web browser where it is displayed. 3. You type in the requested information from your interface and submit it to the Web server. It realizes that the information should be sent to your PHP script that also resides on Sources. 4. The PHP script is executed by calling the binary PHP parser the path to this binary is always included as the first line of the PHP script. During execution, the script retrieves the parameters sent from the Web server. 5. The output of the script is sent to the Web server, which is then sent back to the client Web browser. 3.3 What is PHP? PHP is a recursive acronym for PHP: Hypertext Preprocessor. Its very name implies its close interaction with HTML. If we were using server-side scripting, we could embed PHP code into the middle of HTML such as: <html> <body> <?php echo <p>hello World</p> ;?> </body> </html> The PHP tag looks just like any other HTML tag. Since the output of the PHP is sent to the client, the resulting Web page would look like: <html> <body> <p>hello World</p> </body> </html> Since we will be using command-line scripting, we will not utilize embedded PHP. 2

3.4 Running the examples A typical PHP script will model #!/usr/local/bin/php <?php // php code goes here?> where #!/usr/local/bin/php must be the first line of your file. This line identifies the path to the PHP parser. You will see many errors if this is not the absolute first line of the file. 1 The <?php and?> tags, which might be embedded in an HTML file if server-side scripting is used, tell the parser that the enclosed text should be treated as PHP. You can execute your script by 1. Saving your file in your my php directory as file name.php 2. Checking the permissions of your file. It should look like -rwx x x. To check, type ls -l. To change the permissions, type chmod 711 file name.php. 3. Running your script by typing./file name.php 4 The basics With time and practice, you will find that writing PHP is easy. It comes with a host of predefined functions for commonly used tasks. The PHP parser also manages many of the details that programmers usually worry about. For example, a variable does not need to be manually typed: $bool var = TRUE; // a boolean $str var = foo ; // a string $int var = 12; // an integer $float var = -56.7 // a float Although the programmer does not explicitly declare the types, they are still used by the PHP parser. Thus, dividing a string by an integer may be permitted but makes no sense, and the result should never be used. Furthermore, it is possible to check, set, or cast the type of a variable 2. Each variable must begin with a $ symbol. Also, variable names and function names are case-sensitive. Besides variables, a number of comparison operators are available in PHP. The == operator compares equality of two expressions. Given the following code, if $str var == foo echo str var is foo ; else echo str var is NOT foo ; the script outputs str var is foo. Other comparison operators!=, <, <=, >=, > work as expected. However, there are two additional operators === and!== that compare both value and type. One of these will be explained later in the tutorial. If you have not already noticed, the syntax of the if-statement is similar to the corresponding C/C++ version. A control structure often has more than one valid syntax; yet, the C/C++ equivalent for the following structures will also work in PHP: 3 1 See Section 7 of this tutorial entitled, Debugging your PHP script, for what these errors may be. 2 See http://www.php.net/manual/en/language.types.php#language.types.intro 3 To see alternative syntaxes, visit http://www.php.net/manual/en/control-structures.php. 3

The following is a sample for-statement: if, for, do..while, while, switch for $a = 0; $a < 10; $a++ { echo $a; echo $a * $a; // Compute the square of $a Remember, there is no need to type the $a variable for the first clause. 4.1 s handling is perhaps one of the best features of PHP. There are many array functions, which include searching, splitting, combining, sorting, mapping, padding, shifting, randomizing, etc., that are predefined in PHP. 4 4.1.1 Creation An array can be created with the array... function: $my array = array1, 2, 3, 4, 5; The types of the array elements are not required to be homogeneous. Integers, strings, booleans, floats, and even arrays can be stored as array elements within a single array. The following code is valid: 4.1.2 Element access $my array = array1, cat, 2.34, true, array dog, 17, 4.8; Element access is not different than what you would expect. The cat value can be accessed by $my array[1]. The dog element can be accessed by $my array[4][0]. To view which index accesses which element, insert the following code into your script: print r$my array; The output of this function on $my array as created earlier is: [0] => 1 [1] => cat [2] => 2.34 [3] => 1 [4] => [0] => dog [1] => 17 [5] => 4.8 The following example shows the assignment of an array element to a variable: $foo = $my array[3]; 4 For a complete list, see http://us2.php.net/manual/en/ref.array.php. 4

4.1.3 Key mapping Even more useful than the multiple types in PHP is the concept of key mapping. Consider the following statement: $my array = array101 => 1, my pet => cat, 45 => 2.34, array dog, prime => 17, 4.8; A key value i.e., an index is assigned to each array element. Typical C/C++ or Java arrays begin at index 0. Here, $my array begins with a key of 101. Thus, $my array[101] references the value 1. $my array[ my pet ] references the string cat, and the string cat cannot be referenced by any numerical index. Based on the array declaration, my pet is the only valid index that can reference cat. Note that the nested array element is not explicitly assigned an associated key value. It takes on the key 102, since 101 was the largest numerical index previously used. The array element 4.8 is assigned a key value of 103. Given below is the printout of $my array as created above: 4.1.4 Modifying [101] => 1 [my pet] => cat [45] => 2.34 [102] => [0] => dog [prime] => 17 [103] => 4.8 An existing array element can be modified with: and there are two ways to append to an array: $my array[ my pet ] = turtle ; or $my array[ some new key ] = 10000; $my array[] = 10000; This latter approach assigns 10000 to the key value 104 of my array created earlier. Note that an array does not need to be created with the array function, as in: for $i = 0; $i < 100; $i++ $a new array[] = $i * $i; Once $a new array is created, it can be used in subsequent iterations of the for-loop. 5 Deleting an array element or an entire array is done with: 5 The PHP parser sees the brackets that follow the variable name $a new array and realizes that this variable must be an array. The parser adds the array to its internal symbol table. Initially, key value 0 is assigned an element value of 0 as the result of 0 * 0. In the next iteration, the key value 1 is assigned an element value of 1 as the result of 1 * 1, and so on. If an array is created by element assignment as used above, the index 0 is used as the first key value if no other key value is specified. 5

or unset$my array[45]; // delete an array element unset$my array; // delete the entire array Note that the key-value/array-element-value pair is simply removed from the array. Thus, if we code: $abc = array0, 1, 2, 3; unset$abc[2]; The array now looks like: [0] => 0 [1] => 1 [3] => 3 Making the indices strictly sequential again can be done in several ways. We will provide further explanation in the tutorial. 4.1.5 Strings A powerful aspect of strings in PHP is variable expansion. Consider the following code excerpt: $num = 12; echo The value of \$num is $num. ; This outputs The value of $num is 12. So far, output strings have been enclosed in double quotes. Output strings may also be enclosed in single quotes; however, variable expansion will not work with this method. A third method is the heredoc style. Refer to the manual 6 for more information. To assist the parser, complex variables like arrays must be enclosed within curly braces. 4.1.6 Functions echo my pet is a {$my array[ my pet ] ; A function does not need to be declared before it is used. Functions can best be summarized by an example as follows: echo sum5, 2; function sum$a, $b { return $a + $b; This outputs the value 7. PHP also supports pass-by-reference, variable-length arguments, default argument values, and conditional functions that do not exist until the condition is met. You can also program variable function calls these calls occur when a variable stores the name of a function. The variable is evaluated and the function call is made. Refer to the manual 7 for more information. 6 http://www.php.net/manual/en/language.types.string.php. 7 http://www.php.net/manual/en/functions.php 6

5 Recursive PHP We now illustrate recursive querying by stepping through an example. Suppose we want to find all the flight routes from Montreal to SLC. First, we should specify the path to the PHP parser as follows: #!/usr/local/bin/php Remember, this must be the first line of the file. The next step is to write a starting php tag and to provide information to the Web browser so it can expect HTML or text. See, for example, <?php echo Content-type: text/html\n\n ; Now, we are ready to setup the connection. Note that localhost, listed below, should be typed verbatim. $link = mysql connect localhost, your MySQL user name, your MySQL user password or die Could not connect :. mysql error; The period serves as the concatenation operator. The string returned from the mysql error function is appended to Could not connect :. On a connection success, we should display an appropriate status message: print Connected successfully ; Once we have connected to the MySQL server, we need to specify the name of the database to access. In our case, the name of your database is the same as your MySQL user name. mysql select db your MySQL user name or die Could not select database ; One way to handle the actual recursion is to make a function with a number of arguments, which in our running example include a source city and an array of cities that have been traversed so far. During each iteration, the function finds all the possible destinations from the source and then recurses for each destination. Once the destination, i.e., SLC in our running example, has been reached, we add the route and return to the previous function iteration. We start with the function definition, with the function header looks like the one given below, and then proceed to the function call and variable initialization: function show routes$start city, $already visited { Since we want to store valid routes as we find them, we need an array that is global to the function. The global keyword takes a comma-separated list of variable names. If a global variable already exists, it will be made available to the function. If it does not exist, it will be created once and treated as a global variable. Let s make the query next: global $routes; $query = SELECT dest city FROM flight WHERE source city = $start city ; Notice how simple the actual SQL query is. All of your SQL queries will be relatively simple. The variable $start city will be expanded to its value. It is enclosed within single quotes to preserve MySQL syntax. To execute the query, we use: $result = mysql query$query or die Query failed :. mysql error; The $result variable is a resource a special variable holding a reference to an external resource, which can be a file, image, database link, query result, process handle, XML parsersee http://www.php.net/manual/ en/resource.php for more information for the buffered result of the query. Now we can save each tuple in an array by using the built-in function mysql fetch array... This function returns FALSE once all of the rows have been fetched. The MYSQL ASSOC flag allows us to access the destination city as a row of $tuple[ dest city ]. 7

while $tuple = mysql fetch array$result, MYSQL ASSOC { The $tuple variable is an array with attributes as its keys, and attribute values as its element values. Thus, if we were projecting on dest city and source city, $tuple would contain two key/value pairs e.g., $tuple[ source city ] => Montreal, $tuple[ dest city ] => NY. Once SLC has been reached the final destination in our running example, we append our traversed route to the global $routes array. Consequently, $routes is actually an array of arrays. For example, let s suppose that $already visited the array that stores our current route so far contains: [0] => Montreal [1] => NY [2] => Chicago Now, suppose SLC has been reached. Thus, $tuple[ dest city ] references SLC. We then add SLC to our current route. $already visited now looks like: [0] => Montreal [1] => NY [2] => Chicago [3] => SLC If we add our current route to our global $routes array, $routes will look like: [0] => [0] => Montreal [1] => NY [2] => Chicago [3] => SLC If after some time we find another route, we then append it to $routes. The global $routes array would then look like: [0] => [0] => Montreal [1] => NY [2] => Chicago [3] => SLC [1] => [0] => Montreal 8

[1] => Washington [2] => Kansas-City [3] => SLC To code the behavior described above into PHP, we write: if $tuple[ dest city ] == SLC { $already visited[] = SLC ; $routes[] = $already visited; Ifthe destinationisnotslc,thenweneedtoaddthe destinationtothecurrentrouteandrecurse. However, before recursing, we check to see that we have not already visited this destination in our current route, i.e., else if array search$tuple[ dest city ], $already visited === FALSE { $already visited[] = $tuple[ dest city ]; show routes$tuple[ dest city ], $already visited; The array search... function searches the $already visited array for the value $tuple[ dest city ] and returns the corresponding key, if found. If not found, FALSE is returned. Pay careful attention to the use of the three equal signs. If $already visited has an element that matches $tuple[ dest city ] at index 0 then 0 will be returned. This evaluates to FALSE if just the == operator is used. Yet, if the === operator is used, both the type and the value is checked and FALSE is not returned. It is always a good idea to use the three equal signs with the array search... function. After returning from the recursion, we need to remove the last element of the route the destination we just added and try another destination. In other words, suppose we have added Chicago to our $already visited array. We then check all the cities Chicago can reach. We eventually return back to the sameiterationthat added Chicago to the array. Since wenowwantto checkthoseroutesfromourcurrent point but through another city, we need to remove the Chicago element. Also, if we remove an element, we also remove the corresponding key. To avoid gaps in the key count, we employ the array values... function. It returns an array of values taken from the passed-in array that starts at index 0. unset$already visited[count$already visited - 1]; $already visited = array values$already visited; We can then i call our show routes... function with the right arguments, ii print the result, iii close the connection, and iv include the ending?> tag to match the opening <?php tag. $visited = array Montreal ; show routes Montreal, $visited; print r$routes; mysql close$link;?> 6 The entire PHP script #!/usr/local/bin/php <?php // find the routes from Montreal to SLC 9

echo Content-type: text/html\n\n ; $link = mysql connect localhost, winwardp, winward1010 or die Could not connect :. mysql error; print Connected successfully ; mysql select db winwardp or die Could not select database ; function show routes$start city, $already visited { global $routes, $dest city; $query = SELECT dest city FROM flight WHERE source city = $start city ; $result = mysql query$query or die Query failed :. mysql error;?> while $tuple = mysql fetch array$result, MYSQL ASSOC { if $tuple[ dest city ] == SLC { $already visited[] = SLC ; $routes[] = $already visited; else if array search$tuple[ dest city ], $already visited === FALSE { $already visited[] = $tuple[ dest city ]; show routes$tuple[ dest city ], $already visited; unset$already visited[count$already visited - 1]; $already visited = array values$already visited; $visited = array Montreal ; show routes Montreal, $visited; print r$routes; mysql close$link; 7 Debugging your PHP script A common mistake in writing PHP is to mistype a variable name. PHP simply treats a mistyped variable name as a new variable. PHP is also case-sensitive, so verify that your program is consistent with function names and variable names. To warn about undefined variables, add the following code after the opening <?php tag: error reportinge ALL; If you did not put the PHP parser path in the very first line of the script, you might encounter errors similar to:./testsql.php:?php: No such file or directory./testsql.php: line 4: syntax error near unexpected token routes./testsql.php: line 4: // find the routes from Montreal to SLC 8 Accessing your script through your Web interface After verifying that your script works from the command-line, check that your my php directory has the same permissions as your file. You may access the script from BYU campus computers by using the URL: http://sources-address/ username/your-file.php, where Sources-Address is the link of Sources. You must 10

then input your Sources username and password. Note that you cannot issue a directory listing of my php without explicitly creating something like index.html. This is because of the directory permissions. Listed below are some sample code for creating an HTML <form> tag that accepts input and passes the input to your PHP script:... <form action= mysql-shortest.php method= post > Find the shortest total flying time in minutes from <input type= text name= source city ></input> to <input type= text name= destination city ></input> <input type= submit ></input> </form> <p>... If you place this code in my php/index.html, your interface can be accessed through http://sources- Address/ username. Since this file is executed differently than the PHP script, you should make it readable by others chmod 755 index.html. Alternatively, you can convert it into a PHP script by echoing the necessary HTML tags. The previous code indicates that the two input parameters will be stored into the variables source city and destination city. To access these variables in mysql shortest.php in index.html, use: $start city = $ POST[ source city ]; $dest city = $ POST[ destination city ]; 9 Other tips and examples In computing the cheapest total airfare from one city to another, be sure to include a variable like $price so far in your recursive function header. For each recursion, the current price is added to $price so far and pass this sum as the $price so far parameter for the next iteration. function cheapest$start city, $price so far { global $dest prices, $dest city, $min, $routes; $query = SELECT dest city, airfare FROM flight WHERE source city = $start city ; $result = mysql query$query or die Query failed :. mysql error; while $tuple = mysql fetch array$result, MYSQL ASSOC { if $tuple[ dest city ] == $dest city { if $price so far + $tuple[ airfare ] < $min min =price so far + $tuple[ airfare ]; else if array search$tuple[ dest city ], array keys$dest prices === FALSE $price so far + $tuple[ airfare ] < $dest prices[$tuple[ dest city ]] { if $dest city == ALL $dest prices[$tuple[ dest city ]] = $price so far + $tuple[ airfare ]; cheapest$tuple[ dest city ], $price so far + $tuple[ airfare ]; When computing the cheapest airfare from one city to all the other cities, use a global array with keys set to the destination cities. The value should be the cheapest airfare so far to reach that destination. This can be done as follows: 11

$dest prices[$tuple[ dest city ]] = $price so far + $tuple[ airfare ]; If the array $dest prices does not have a certain key, such as $dest prices[ NY ], the new key and its associated value are added to the array. To check if an arraycontainsa particular destination as a key, you can use the array keys... function in conjunction with the array search... function. The array keys... function simply returns an array of the keys of the passed-in array. As an example, refer to the code fragment under the first tip. To traverse through each element of an array, you can do something as follows: foreach$my array as $array element echo $array element; or foreach$my array as $key => $array element echo my array[$key] => $array element ; To customize the appearance of your output besides using print r..., you can output HTML tags: echo <table>\n ; while $line = mysql fetch array$result, MYSQL ASSOC { echo \t<tr>\n ; foreach $line as $col value { echo \t\t<td>$col value</td> \n ; echo \t</tr>\n ; echo </table>\n ; Note that since you will ultimately access your script through a Web browser, certain HTML tags, such as <table>, <td>, and <tr>, must be included for the Web browser to display the output in a table. Without these tags, the HTML parser would produce one long line of data regardless of what row or column the data originated, since it ignores white space. The following function is helpful to compute the difference in minutes between two military times: function time diff $dept time, $arr time { /* A flight that left at 7 AM and arrived at 5 AM the next moring would have traveled for 22 hours. To compute this, first use 0500 + 2400 = 2900 and then 2900-0700 = 2200 */ if $arr time < $dept time $arr time += 2400; // Now, separate military times into hours and minutes to extract the hours for 14:36, // 14 = int 1436 / 100. To extract the minutes for 14:36, 36 = 1436-14 * 100 $arr hours = int$arr time / 100; $arr min = $arr time - $arr hours * 100; $dept hours = int$dept time / 100; $dept min = $dept time - $dept hours * 100; // return time difference in minutes // 14:36-16:37 = 38:36-16:37 = 36 + 38-16 * 60-37 = 1319 minutes return $arr min + $arr hours - $dept hours * 60 - $dept min; 12

If you need to erase a global array using unset$my array, be sure to make it global i.e., global $my array before referring to it again. Youcanusethe Linux cp commandtocopyanexistingqueryasanewqueryandavoidasubsequent chmod command. For greater efficiency and legibility, place your function definitions in one PHP script that can be accessed much like a #include or import in C++ and Java. This library file should have the same permissions as your other PHP scripts; however, do not specify the path to the PHP parser in this file. In your PHP scripts that call the library functions, use require library-file-name.php ; This code can be placed anywhere between the <?php and?> tags but must be placed before the function calls. Your library functions are then called in the normal manner. Remember: the path to the PHP executable must be on the very first line of your PHP script. Also, remember to have access rights on your PHP files set to 711 granting additional rights can actually render them unusable 10 Notes specific to Sources To allow http access on Sources, you must create your my php directory in your home directory, and both your home directory and my php/ must have permissions set to drwx x x. My php/ is mapped to http://sources-address/ <your user name>/, so files with the proper permissions744 for HTML files, and 711 for PHP in my php/ will be accessible through the web at this address, with the appropriate file name appended. Remember that Sources is set up to only allow http access to computers on the same network ie. those in the cs.byu.edu domain. There are small differences between ORACLE and MySQL. For example, ORACLE requires that you use NUMBER as a general type for numerical values, while MySQL requires that you use more specific types, such as INT, INTEGER, or FLOAT. Please be extra careful to avoid infinite loops/recursion and other CPU intensive activity; a lot of students use Sources, and as such, it will affect others if you overload it. Just a warning. 11 References Refer to www.php.net/manual/en/langref.php for a reference on the basics of PHP. Other references include http://hotwired.lycos.com/webmonkey/programming/php/ PHP and MySQL references. http://www.phpbuilder.com/ http://php.resourceindex.com/ http://www.mysql.com/doc/en/index.html A MySQL reference. 13