Open source software security

Beginners Guide to PHP

30 November -0001

PHP

Training material
September 24, 2001


Table of Contents:
Installing PHP
How PHP Works
How PHP is Prepared
PHP Simple Language Syntax
Comments
Variables
Terminating Statements
Variables and Operators
General Operators
Assignment Operators
Comparison Operators
Logical Operators
Basic PHP Flow
While Loops
Nesting Loops
For Loops
Passing Variables in Forms & URLs
PHP Database Interaction (MySQL)
Conclusion

Installing PHP

-top-

Installation on Linux

Installing PHP on Mandrake or Red Hat Linux is very easy because of the RPM (RedHat Package Manager) features of both of these distributions. To install PHP you will need a working Apache server running. Apache has its own RPMs, but is installed by default on many Linux servers.

To install PHP you need to install the following RPM's:

php This is the essential PHP RPM. The RPM on Mandrake 8.0 is php-4.0.4p11-6mdk
mod_php This is the Apache module needed by the server to interpret PHP in HTML served from the Apache web server. The RPM on Mandrake 8.0 is mod_php-4.0.4p11-6mdk
php-common This is the library of common functions for PHP. The RPM on Mandrake 8.0 is php-common-4.0.4p11-6mdk
And finally:
php-mysql These are the PHP functions for interaction with a MySQL database. The RPM on Mandrake 8.0 is php-mysql-4.0.4p11-6mdk. Of course you will only need this RPM if you intend to use MySQL as your database back-end.


To find out if these packages are installed simply type:

rpm -q packagename

where 'packagename' is the name of the package you want to check: for instance:

rpm -q php-common

will check to see if the package php-common-4.9.4p11-6mdk is installed on Mandrake 8.0. To install a package all you need to do is su to root, or log in as root, and issue

rpm --install packagename

where the 'packagename' is the full package name of the RPM you wish to install (i.e. 'rpm --install php-4.0.4p11-6mdk.i586.rpm'). This will check package dependencies and install the necessary package for you. Be sure to install all the necessary packages before you continue.

Installing on Another OS or Distro

If you are installing PHP on a system other than Red Hat or Mandrake or you don't have the appropriate RPM's you'll need to download the binaries and compile them using the instructions from http://www.php.net.

How PHP Works

-top-

PHP stands for Personal HomePage (or PHP Hypertext Preprocessor, depending on your sources), a server side scripting language. PHP is an open source project available for use on most common web servers (Apache, IIS, etc.). PHP's official homepage is http://www.php.net. Because it is server side, PHP is never visible to end-users. Viewers of PHP pages will only be aware of PHP in a URL file extension of .php. PHP operates on a web server and essentially interprets server side scripting. This means that requests to a web server from a browser are received, the server selects the appropriate page, and then PHP prepares the HTML to be returned to the browser. At the stage where PHP prepares HTML, the PHP scripting language allows a web server to dynamically render an HTML page based on programmers' instructions. The major advantage over HTML offered by this configuration is that while HTML is static and must be changed manually, PHP allows for dynamic changes to .php pages prepared by a server. This would allow a web programmer to prepare a page that varied appearance based on the day of the week, time of day, or current data in a remote database, simply by writing appropriate PHP code, rather than manually changing an HTML page for each instance of variation. It is important to understand this concept in order to properly code PHP pages. Illustrated below is the path a client makes to the web server and its return response:

  client   -------->   server
 (browser)


Response:

 server  -->PHP---------> client


In essence, PHP stands between the client and server and prepares HTML documents on the fly, based on user requests and PHP code guidelines. This allows for PHP to respond to web developer and client responses, a PHP homepage could be coded to respond to multiple variables, for instance:

  1. if it is Tuesday, return the to user a homepage with a black background
  2. if it is Friday, return to the user a homepage with a blue background in all other circumstances the page should have a white background


PHP can also be used to change pages dynamically based on database information. This is perhaps the most powerful aspect of PHP. PHP can be used, for instance, to return a homepage with the following instructions:

  1. if the requesting user's IP address is in the databases IP table, redirect the user to another page.
  2. if the user is unknown display information requesting them to register as a user
  3. if there is information in the database with the same date stamp as today, display that data on line 13 of the page


These sorts of instructions allow for a much finer degree of control by a coder over the display, flow and functionality of not only individual pages, but also of a web site as a whole. Users whose IP address reflects that they are in a French speaking country could be redirected to a French version of the website, pages could be updated based on the latest information inserted into a database, user requests to the page could even be tracked by PHP.

How PHP is Prepared

-top-

PHP is an embedded language. PHP scripts are inserted directly in HTML code. While standard HTML tags are delimited by less than and greater than characters, such as:

<html>


PHP must be distinguished separately. Since all material between less than (<) and greater than (>) symbols is escaped (does not appear) in HTML display, PHP follows suit. The only difference is that the beginning and closing characters which surround PHP code are slightly more involved. Much like Active server Pages use less than, percent to delimit its code, such as:

<% .asp code %>

PHP uses:

<?php PHP code ?>

less than, question mark, 'php' and question mark, less than to delimit php code. Thus the following:

<html>
<body>
<?php
	print "hello world";
?>
</body>
</html>


is a standard HTML page that includes PHP code. You will notice that the '<?php' and '?>' do not have to appear on the same lines, or even directly preceding and following PHP code. Just as HTML ignores white space, so too does PHP ignore white space. The use of line breaks and indention should only be a consideration in reading your own and others' PHP code. Incidentally, because PHP is invisible to the end user and prepared by the server, the page above would produce a blank web page with the words 'hello world' on it. If the end user viewed the page source, all they would see would be:

<html>
<body>
hello world
</body>
</html>


You should note that this is the exact HTML code passed from the server back to the user. All PHP code is interpreted by the server, and only appropriate HTML (without any PHP) is rendered and passed back to the user.

PHP Simple Language Syntax

-top-

Language Syntax:

LANUGAUGE SYNTAX -- COMMENTS

All PHP embedded between the '<?php' and '?>' is encoded using standard PHP language conventions. The simplest of these conventions is commenting. Comments are instructions, advice, or simply comments used by programmers and ignored by PHP. PHP has two conventions for coding comments: single line comments and multi line comments. Single line comments are coded using either double slashed or a pound sign. For example, the following are both legal single line comments:

// comment here
# comment here

Multi line comments are surrounded by a slash and asterisk ('/*' to begin the comment and '*/' to close the comment). The following is an example of a legal multi line comment, note that all material between the opening multi line comment (/*) and closing multi line comment (*/) is ignored, even if it includes legal PHP commands:

/*
	This is a legal multi line
	comment.  Even code such as:
	print "hello world";
	will be ignored by PHP as it
	prepares the HTML page from
	PHP code.


Note that multi line comments can be used to surround single line comments as well:

/* This is a legal single line comment */

LANGUAGE SYNTAX -- VARIABLES

Variables are dynamic objects used to hold a variety of data, either static or dynamic. Variables in PHP are easily identified by the dollar sign that precedes the variable. For example:

$bob
$a
$holder_12

are all valid variables. Note that PHP *is* case sensitive. Thus:

$bob
$Bob

are two separate variables. In naming variables only alphanumeric characters and underscores are legal. So:

$to@me.com

is *not* a legal variable.

LANGUAGE SYNTAX --TERMINATING STATEMENTS

In PHP all statements must be terminated by a semicolon. It does not matter if a statement is a single or multi-line statement, but omission of a semicolon at the end of each statement will cause a 'parse error' that will cause the PHP to fail. The following is a valid series of PHP statements:

<?php
	$bob = "bob";
	print $bob;
?>


Note the semicolons marking the end of each statement. Get in the habit of using semicolons frequently in your PHP code, and on indications of a parse error, your first look at faulty PHP code should include a quick scan for all the necessary statement terminating semicolons.

Variables and Operators

Variables, Operators, and Understanding PHP Flow
-top-

Variables can easily be described as an empty glass. Any variable can contain almost any information, and this information can be changed at any time in a PHP program. Assigning a variable a value is as simple as:

$username = "bob";

This statement assigns the string value of 'bob' to the variable $username. Thus:

$username = "bob";
print $username;
Will return:

bob

Note that PHP flows from beginning to end and variables can be reassigned at any time. Thus:

$username = "bob";
$username = "jena";
print $username;

will return:

jena

rather than 'bob'. This is because the variable was first assigned the string value of 'bob' but then reassigned a new value of 'jena'. This is true of numeric values of variables as well. Thus:

$someVar = 1;
$someVar = $someVar + 30;
print $someVar;

will return:

31

General Operators



-top-

Operators are symbols which perform a function inherently defined by PHP. Operators come in several types and are an integral piece of PHP. PHP also includes a number of types of operators. The Mathematical Operators in PHP include:

OperatorDescription
+The addition operator. Performs mathematical addition of numeric values
-The subtraction operator. Performs mathematical subtraction of numeric values
*The multiplication operator. Performs mathematical multiplication of numeric values
/The division operator. Performs mathematical division of numeric operators
%The modulus operator. Returns the remainder after a number to the left of the operator is divided by a number to the right of the operator
++The increment operator. Increments the variable preceding the operator by one
--The decrement operator. Decrements the variable preceding the operator by one


Examples of the use of each of these are as follows, assume $a = 2:

$a + 2returns4
$a - 1returns1
$a*5returns10
$a/4returns0.5
9%$areturns1
$a++reassigns$a = 3
$a-- reassigns$a = 1


The concatenating operator is a period ('.'). The concatenating operator is used to add string character values together. Regardless of the data type of operands, they are treated as strings when concatenated. For instance:

"hello " . "world"

Returns:

hello world

and:

"5" . "4"

returns the string:

54

Note that the concatenating operator will not add white space between concatenated strings, thus if you desire white space you need to include it manually.

Assignment Operators:

The most common assignment operator (=) has already been introduced. An assignment operator is used to assign a value to a variable. PHP defines the equal sign as an assignment operator and automatically understands the use of the equal sign to set the value of a variable. Other assignment operators include:

+=increments a variable to the left of the assignment operator by the value to the right
-=decrements a variable to the left of the assignment operator by the value to the right
/=reassigns the value of a variable to the left of the operator to a new value equal to the value of the original value divided by the number to the right of the operator
*=reassigns the value of a variable to the left of the operator to a new value equal to the value of the original value multiplied by the number to the right of the operator
%=reassigns the value of a variable to the left of the operator to a new value equal to the value of the remainder left by dividing the original variable by the number to the right of the operator
.=reassigns the variable to the left of the operator to a new value equal to the original value with the string to the right of the operator concatenated to it


Examples of each of the previous are as follows (assume $x = 3):

$X += 2same as$x = $x + 2resets $x to 5
$x -= 2same as$x = $x - 2resets $x to 1
$x /= 2same as$x = $x / 2resets $x to 1.5
$x *= 2same as$x = $x * 2resets $x to 6
$x %= 2same as$x = $x % 2resets $x to 1
$x .= "foo"same as$x = $x"foo"resets $x to "3foo"


Comparison Operators:

Comparison operators are used to test the values of variables. These are most commonly used in flow control, but since we're on the topic of operators we should introduce comparison operators now. Comparison operators don't reassign variable values like the above operators, but simply test a situation, then PHP can be used to issue commands based on the outcome of the comparison.

>greater than: Variable x is greater than five$x>5
<less than: variable x is less than five$x<5
>=less than or equal to: variable x is less than or equal to five$x<=5
>=greater than or equal to: variable x is greater than or equal to five $x>=5
==equivalent: Variable x is five$x==5
!=not equivalent: Variable x is not five$x!=5
===same value and type: X is of the same value and type as string "foo" $x==="foo"


Don't worry about comparison operators too much until you get to flow control. These sorts of operators are used to make PHP statements such as: "If variable x is not equal to 5 then pop this alert box" -or- "If variable username is a string equal to "admin" then redirect the user to the administration page."

Logical Operators:

Comparison operators are often used in conjunction with logical operators. Again, this is most commonly used in flow control. Just keep these in mind for later.

||or
oror
xorXor Left or Right are true but not both
&& and
andand
!not


These bear further explanation by example to make more sense:

Statement: If x is greater than 12 OR x is less than 20 print the words: "you're a teen"
Code Example:
if ((x > 12) || (x < 20))
{print "you're a teen";}

Statement: If x is greater than 19 and x is less than 30 print the words: "you're in your 20's"
Code Example:
if ((x > 19) && (x < 30))
{print "you're in your 20's";}

Statement: If x is less than 5 or x is less than 0 but not if x is less than 5 AND x is less than zero print "hmm". Meaning if x equals 3 "hmm" will be printed, but if x is equal a negative number "hmm" will not appear. This is a very rare operator.
Code Example:
if ((x < 5) xor (x < 0))
{print "hmm";}

Statement: If the variable x doesn't exist (i.e. hasn't been declared as a variable) print "you're not four"
Code Example:
if (!$x)
{print "you're not four";}

BASIC PHP FLOW

-top-

As you may have already determined, PHP flows in a linear fashion. PHP is not an object oriented language, but rather shares a flow common to languages like BASIC or Javascript. This means that the program runs from start to finish, in that order. Thus:

$var = "foo";
$var = "bob";
$var = "bar";
print $var;

Will leave execute and return an HTML page with the word "bar" in it. While there are ways to alter the flow of a PHP script as we will see later, in the end PHP pages will start at the top, and execute on down to the end of the program.

Looping in PHP
FLOW CONTROL - TESTING EXPRESSIONS AND USING LOOPS

Flow control is used for dynamic output. Flow control basically interrupts your PHP program, evaluates a condition, and continues the program based on how the condition was evaluated. For instance, lets say you wanted to write a PHP page that displayed a page with a background color that was predefined by a user. The page might appear as follows:

<html>
<body> <?php
		if ($bgcolor == "blue")
			{print "bgcolor='#000099'";}
		elseif ($bgcolor == "red")
			{print "bgcolor='#990000'";}
		else 
			{print "bgcolor='white'";}
	?>>
Some text
</body>
</html>


If the string $bgcolor happened to be equal to "blue" the following HTML would be returned to the user:

<html>
<body bgcolor='#000099'>
Some text
</body>
</html>


Using this example you can also see how PHP can be used to dynamically choose material to display on a requested HTML page, and also how the PHP code is hidden from the end user.

The most basic type of flow control, that represented above, is the 'if then' statement. This type of flow control is summarized as "If this condition is true then do this thing." The 'if then' statement can also be expanded by using 'else.' For example you could code the statement "If this condition is true do this thing, otherwise do this other thing' using 'else.' 'elseif' may be used for a finer degree of control. Let us use another example to demonstrate the versatility of the 'if then' statement. Let us say that I want to code PHP to reflect the following statement:

Statement
If variable x is equal to "sad" print the words "don't be sad", otherwise print the words "I'm glad you're happy"
Code Example
	if ($x == "sad")
		{print "don't be sad";}
	else
		{print "I'm glad you're happy";}


Now for a demonstration of more complex flow control with the 'if then' statement:

Statement
If variable weather is equal to "cloudy" print the words "Tut tut it looks like rain", if variable weather is equal to "rain" print the words "better have an umbrella", if variable weather is equal to "cold" print the words "bundle up", in all other cases print the words "looks just fine out."
Code Example
	if ($weather == "cloudy")
		{print "Tut tut it looks like rain";}
	elseif ($weather == "rain")
		{print "better have an umbrella";}
	elseif ($weather == "cold")
		{print "bundle up";}
	else
		{print "looks just fine out";}


You can see that you can refine PHP's response to a number of conditions using 'if else'. Notice also that unless the conditions in the 'if' or 'elseif' statements are not met, then the commands proceeding the 'else' statement are issued. You can consider the 'else' portion of the 'if then' statement to be the default that will execute if all else fails. Note also the use of comparison operators in the above example. These are essential for flow control. Take the following example for a more detailed view of the comparison operators in action:

Statement
If the variable weather is equal to "cloudy" or equal to "cold" or equal to "rain" then print the words "the weather is bad", otherwise print the words "the weather is fine!"
Code Example
	if (($weather == "cloudy") || 
	    ($weather == "cold") || 
	    ($weather == "rain"))
		{print "the weather is bad";}
	else
		{print "the weather is fine!";}


As you can see, the 'if then' statement is a powerful tool for flow control.

THE WHILE LOOP

Another common form of flow control is the loop. In a loop a piece of code will execute, and continue to execute until a certain condition is met. This is mainly used for scanning through a set of data or executing a piece of code a set number of times. The while loop contains two parts, the condition checking piece and the code to execute. Let us say we want to print out the words "happy birthday" ten times, this could be accomplished by typing out the words ten times on the page, but could be automated much more quickly by using a loop.

Code Example
	$counter = 1;
	while ($counter <=  10)
		{print "happy birthday";
		 $counter++;}


This piece of code first sets a variable equal to one, then it sets out a condition. While the counter variable is less than or equal to 10 the code piece delimited by the '{' and '}' is executed. First the program prints the words "happy birthday" then the variable counter is reset to one number higher. The resulting HTML might look like this:

<html>
<body>
happy birthdayhappy birthdayhappy birthdayhappy birthdayhappy birthdayhappy birthdayhappy 
birthdayhappy birthdayhappy birthdayhappy birthday
</body>
</html>


Not very impressive, but its a start. If we wanted line breaks between the "happy birthday" pieces we could change the code to:

Code Example
	$counter=1;
	while ($counter <= 10)
		{print "happy birthday
"; $counter++;}


and this would change the resulting HTML from one long string to a list of "happy birthday" pieces separated by new lines.

NESTING LOOPS

It is very possible to nest loops for a further degree of flow control. For instance, lets say we want to print out a countdown from 10 to 0, but instead of printing out the number 5 we want to print out the number five and the words "half way there". We could use a nested loop to achieve this result. The PHP would be as follows:

<html>
<body>
<?php
	$countdown = 10;
	while ($countdown >= 0)
		{
			if ($countdown != 5)
				{print $countdown;
				 print "<br/>";}
			else
				{print $countdown." half way there";
				 print "<br/>";}
		 $countdown++;
		}
?>
</body>
</html>


This code example would return the following HTML page to a user who requested the URL:

<html>
<body>
10<br/>
9<br/>
8<br/>
7<br/>
6<br/>
5 half way there<br/>
4<br/>
3<br/>
2<br/>
1<br/>
0<br/>
</body>
</html>


You can nest as many loops as you like in order to increase your flow control.

THE FOR LOOP

The 'for' loop is a much more intricate and powerful looping mechanism. It is dissimilar in syntax and appearance only in its first lines. The code to execute between the '{' and '}' characters is much the same as that which we have used before. The syntax of a for loop is as follows:

for (variable; test; increment)
	{
	 code
	}


We can use the for loop to execute the following statement:

Statement
set variable x to 4. While x is less than 10 print out x and increment x by 2
Code Example
	for ($x=4; $x<10; $x+=2)
		{print $x;}


Using for loops you can not only loop over elements, but you can also use the special 'break' statement to exit the loop. This is especially useful for error trapping. For example, let us use the above example but add one condition that if met will end the loop prematurely.

Statement
set variable x to 4. While x is less than 10 print out x and increment x by 2. if x is found to be equal to 8 however, terminate the loop Code Example
	for ($x=4; $x<10; $x+=2)
		{
			if ($x == 8)
				break;
		 print $x;}


Another piece of additional control over the for loop is offered with the continue statement. This again is useful for error trapping. Lets say we want take a number and multiply it by a series of numbers starting with 2 incrementing by one until that number reaches 10 but we want to avoid multiplying that number by 5. For this case we could use the following code:

Code Example
	for ($x=2; $x<11; $x++)
		{
			if ($x == 5)
				continue;
		print $x*5;
		}


Passing Variables in Forms & URLs

-top-

PASSING VARIABLES -- FORMS AND URL

To utilize PHP's enormous capabilities you are most likely going to want to use forms to handle user input. Forms are a very easy way to take user input and pass it to PHP variables. The method in which PHP passes form variables is very straightforward and simple to use. For instance, let us say that we want to have a form that will take a username and password from a user of a site. For the sake of this example let us use the following form (saved as form.php):

<html>
<body>
<form method="post" action="form2.php">
Username: <input type="text" name="uname"><br/>
Password: <input type="password" name="pw"><br/>
<input type="submit"><input type="reset">
</body>
</html>


Once this information is filled out and the user hits the submit button, the form data will get 'posted' to 'form2.php' as per the instructions in the <form> tag. Let us say we only want to allow users who enter the username 'admin' and the password 'secretWord' to view the data on form2.php, and all others to be redirected back to the form.php page to retry their password. Form2.php could be coded as:

<html>
<head>
<?php
     if (($uname != "admin") && ($pw != "secretWord"))
	{print "<script>alert('Sorry, wrong username/password');";
	print "location.href='form.php';</script>";
	}
?>
</head>
<body>
Welcome to the admin screen!
You entered the correct username: <?php print $uname; ?> and password: <?php print 
$pw; ?>
</body>
</html>


You will notice that the form variables passed to the second page are passed as the name of the form field preceded by a $ sign. Thus if you have:

<input type="text" name="thisVar">


It would be passed when the information was posted to the form action page as:

$thisVar

URL variables are passed in much the same way. URL variables are usually passed in href anchor tags, and are always in the format:

location.ext?var1=value1&var2=value2&var3=value3

where 'location' is the page name, '.ext' is the file extension of the destination, 'var1' through 'var3' are the variable names (without $ symbols, or if they include string symbols they must be handled specially), and 'value1' through 'value3' are the values assigned to each respective variable. Note that you can pass as many variables as you like through URL, the list must start with a '?', however, and proceeding variables are delimited by the '&' symbol.

Once URL variables are passed they are called in much the same way as form variables. For instance, let us say the following link is coded on a page:

<a href="destination.php?id=331&name=John&age=54">Destination</a>


The page 'destination.php could call the following variables simply by instantiating them with the same name specified in the URL but with the '$' sign preceding them:

>
<?php
	print $id;
	print "<br/>";
	print $name;
	print "<br/>";
	print $age;
?>


Would print the following on the destination.php page:

331
John
54

PHP Database Interaction

-top-

One of PHP's most powerful tools is the ability to connect to a database and return results dynamically based on database contents. This section will focus on PHP and its connectivity with MySQL. This connection is not necessarily as straight forward as with other tools. Database connectivity can be as simple as:

<?php
	$link = mysql_connect( "localhost", "username", "password");
	mysql_select_db("database", $link);
	$query = mysql_query( " select * from tablename" );
	while ($result = mysql_fetch_array($query))
		{print "$result[tablefield] <br/>";}
	mysql_close($link);
?>


This piece of PHP has several steps but accomplishes a simple task: querying the table 'tablename' and retuning the field 'tablefield.' In order to make the example more concrete let us assume that we need to pull information from the following table:

Table_user
User_id		User_firstname		User_lastname
1		John			Doe
2		Daniel			Stein
3		Sandra			Clove


For this example we will want to pull the user names and present then in an unordered, bulleted list. Let us assume that this table is in a database named 'SampleDB' and the MySQL daemon is set up with a user with the name 'root' and the password '21jump'. To accomplish this task we could use the following HTML page:

1.<html>
2.<body>
3.<ul>
4.<?php
5.	$user = "root";
6.	$pass = "21jump";
7.
8.	$open_datalink = mysql_connect("localhost",  $user, $pass );
9.
10.	//If the database cannot be connected to throw an error
11.	if (! $open_datalink)
12.		die( "Couldn't connect to database server");
13.	
14.	$database = "SampleDB";
15.
16.	//Select the appropriate database from the server or throw error
17.	mysql_select_db ($database) 
		or die ( "Couldn't connect to database");
18.
19.	$query = mysql_query("select user_firstname, 
		user_lastname from table_user");	
20.	
21.	//Print out the results
22.
23.	while ($result = mysql_fetch_array($query))	
24.		{
25.		print "<li>$result[user_firstname]
		 $result[user_lastname]</li>";
26.			}
27.		mysql_close($open_datalink);
28.	?>
29.	</ul>
30.	</body>
31.	</html>


Let us step through this code line by line now. Line 4 opens the PHP section of the page, and line 28 closes that portion, the preceding and following lines are regular HTML. Line 5 sets a variable called user with the appropriate username to connect to the database. Line 6. sets a variable with the database password. Line 8 begins the database connection. The $open_datalink variable is an arbitrarily named variable (as $user and $password are) but 'mysql_connect' is the native PHP command that is used to connect to the database. The syntax for mysql_connect is:

mysql_connect(server, user, password);

Line 11 sets up a graceful exit from the PHP function in case the database connection fails. 'Die' tells the PHP script to give up and throw the error specified on line 12, a more informative error than the native PHP error. Notice that lines 11 and 12 use an 'if' loop to control the flow, the '!' character indicates 'not.' Without an 'else' clause in this statement the script will continue on with its task if the criteria in line 11 is not met. In other words "if the database connection is not present (which would result in the variable $open_datalink not being present), throw an error and exit the script." Line 14 sets up an new variable that is assigned the name of the database (for use in later statements). Line 15 contains another native PHP command: mysql_select_db. This command can only be executed after a successful connection is created. The syntax for this command is:

mysql_select_db(DatabaseName);

Again, this statement is combined with an error trapping clause using the 'or' operator. If the command fails this statement will throw the error "Couldn't connect to database." At this point in the script an open database connection exists and a specific database has been selected to query. Line 19 sets up a new variable called '$query' and assigns it a value containing another native PHP statement. '$query' is assigned: 'mysql_query("select user_firstname, user_lastname from table_user");' which is a combination of a proper Server Query Language statement and the native PHP function 'mysql_query'. Because this particular query returns a number of results (a record set) we must parse the results into an array in order to display them. Lines 23 to 26 do this by first assigning the $result to a mysql_fetch_array function (again native to PHP) and passing the results into the array one by one. Using the while statement we are able to call each result in order. Because the returned record set contained several pieces of information per line, the array is multidimensional. In order to pull the appropriate piece of information from each array value we use the sysntax: $result[table_column_name] where "table_column_name" is the name of the column in the tabled queried by the mysql_query function.

To review: there are several steps in calling information from a database using PHP. First we must open a connection to the MySQL server, then we must select a specific database. Next we fire a query at the database. Finally we parse the results into an array for display and loop over that array in order to display all the results. Again:

* Connect to the database
* Select a database
* Query a table in the database
* Parse the resulting record set into an array
* Loop over the array to display the results

Note that if your query is a simple insert or update, there is no record set to return and you can skip the last two steps. For instance, let us say we prepare the following HTML form in order to insert a user's first and last name into a table named 'userinfo' in database 'test' and that the table 'userinfo' that has two columns, one named 'user_firstname' and the other 'user_lastname'. We first use the HTML page:

<html>
<body>
<form method="post" action="script.php">
First Name:  <input type="text" name="firstname"><br/>
Last Name:  <input type="text" name="lastname"><br/>
<input type="submit">
</form>
</body>
</html>


When a user hits the submit button the information gets passed to the 'script.php' page that we code thus:

<?php
	$user = "root";
	$pass = "21jump";
	$open_datalink = mysql_connect("localhost",  $user, $pass );
	//If the database cannot be connected to throw an error
	if (! $open_datalink)
		die( "Couldn't connect to database server");
	
	$database = "test";
	//Select the appropriate database from the server or throw error
	mysql_select_db ($database) 
		or die ( "Couldn't connect to database");
	
	mysql_query("insert into userinfo 
		(user_firstname, user_lastname) values 
('$firstname', '$lastname'");
?>


Notice how we simply fired a query at the table using the mysql_query command and didn't need to call any variables or handle and return recordsets.

It is worth mentioning at this point that since the PHP scripts stored on your web server contain valid usernames and passwords to connect to your MySQL server. For this reason it is EXTREMELY important that you guard these documents from unauthorized users. If a malicious attacker were to download these pages they would plainly be able to see usernames and passwords listed. Also keep in mind that if you FTP your PHP pages to and from a server they are being sent in clear text and these transmissions are liable to being intercepted, again revealing usernames and passwords to connect to your MySQL server (allowing an attacker to alter tables that may be used for either MySQL access or tables of information for display on your web pages).

Conclusion

-top

This should give you more than enough information to create dynamic web pages using PHP. Remember that PHP is a community of developers and the web contains some very useful links for PHP help and code examples. The PHP main website at www.php.net provides a wealth of resources for learning and troubleshooting as well as further links to explore the vast array of PHP functionality.