Tuesday, August 11, 2009

Data In, Data Out

HP and MySQL work very well together. This dynamic partnership is what makes PHP and MySQL so attractive for Web database application
development. Whether you have a database full of information that you want to make available to users (such as a product catalog) or a database waiting to be filled up by users (for example, a membership database), PHP and MySQL work together to implement your application.

One of PHP’s strongest features is its ability to interact with databases. It pro­ vides functions that make communicating with MySQL extremely simple. You use PHP functions to send SQL queries to the database. You don’t need to know the details of communicating with MySQL; PHP handles the details. You only need to know the SQL queries and how to use the PHP functions.

In previous chapters of this book, I describe the tools that you use to build your Web database application. You find out how to build SQL queries in Chapter 4 and how to construct and use the building blocks of the PHP lan­ guage in Chapters 6 and 7. In this chapter, you find out how to use these tools for the specific tasks that a Web database application needs to perform.

PHP/MySQL Functions

You use built-in PHP functions to interact with MySQL. These functions con­ nect to the MySQL server, select the correct database, send SQL queries, and perform other communication with MySQL databases. You don’t need to

know the details of interacting with the database because PHP handles all the details. You only need to know how to use the functions.

At the present time, PHP (beginning with version 5) has two sets of functions for interacting with MySQL. One set of functions is used to interact with MySQL version 4.0 or earlier. The other set of functions is used to interact with MySQL version 4.1 or later.

Throughout the book, my examples and programs show the functions that work with MySQL version 4.0. At the time of this writing, the current stable version of MySQL is version 4.0. In addition, the PHP functions for use with MySQL version 4.1 are described in the documentation on the PHP Web site as experimental, with a warning: Use this extension at your own risk. At the present time, MySQL version 4.1 is available only as alpha software, defined in the MySQL manual as follows: The release contains some large section of
new code that hasn’t been 100% tested. Therefore, I am writing this book based on the use of MySQL 4.0 and the PHP functions that work with this version.

The PHP functions for use with MySQL 4.0 have the following general format:

mysql_function(value,value,...);

The second part of the function name is specific to the function, usually a word that describes what the function does. In addition, the function requires one or more values to be passed, specifying things such as the database con­ nection, the data location, and so on. The following are two of the functions that are discussed in this chapter:

mysql_connect($connect);
mysql_query(“SQL statement”,$connect);

By the time you read this book, MySQL 4.1 might be the current stable ver­ sion of MySQL. If so, you can use MySQL 4.1 and the functions that work with it. As of this writing, the functions discussed in this book are the same for MySQL 4.0 and MySQL 4.1 except for a change in name. The names of the functions for use with MySQL 4.1 begin with mysqli_ rather than mysql_. Thus, the functions shown above would have the following names if used with MySQL 4.1:

mysqli_connect($connect);
mysqli_query($connect,“SQL statement”);

The functionality and syntax of the functions are the same or very similar. For instance, notice the difference between the two following functions:

mysql_query($sql,$connect)
mysqli_query($connect,$sql)

Notice that the order of the items passed is different. This is true for several functions.

This discussion refers to the mysqli functions as they are now. The mysqli functions can change, of course. If one of the mysqli functions doesn’t seem to work as it should, check the manual for any possible differences in usage.

The i added to the name stands for improved; this set of MySQL functions is provided by the improved MySQL extension. At this time, support for mysqli is not included with PHP by default. It must be enabled when PHP is installed. However, by the time MySQL 4.1 is the stable release, it’s likely that mysqli will be part of PHP without your needing to enable it specifically. To see the current status of mysqli, check the documentation at www.php.net/manual/ en/ref.mysqli.php.

As of this writing, you can use this installation option to enable mysqli:

--with-mysqli=DIR

DIR is the path to the directory where a program called mysql_config, which was installed when MySQL 4.1 was installed, is located.

Making a Connection

Before you can store or get any data, you must connect to the database. The database might be on the same computer with your PHP programs or on a different computer. You don’t need to know the details of connecting to the database because PHP handles all the details. All you need to know is the name and location of the database. Think of a database connection in the same way that you’d think of a telephone connection. You don’t need to know how your words move between telephones. You only need to know the area code and phone number. The phone company handles the details.

After connecting to the database, you send SQL queries to the MySQL data­ base by using a PHP function designed specifically for this purpose. You can send as many queries as you need. The connection remains open until you specifically close it or the program ends. Similarly, in a telephone conversa­ tion, the connection stays open until you terminate it by hanging up.

Connecting to the MySQL server

The first step in communicating with your MySQL database is connecting to the MySQL server. To connect to the server, you need to know the name of the computer where the database is located, the name of your MySQL account, and the password to your MySQL account. To open the connection, use the mysql_connect function as follows:

$connection=mysql_connect(“addr”,”mysqlacctname”,”password”)
or die (“message”);

Handling MySQL errors

You use the mysql functions of the PHP language, such as mysql_connect and mysql_query, to interact with the MySQL database. If one of these functions fails to execute correctly, a MySQL error message is returned with information about the problem. However, this error message isn’t sent to the browser unless the program deliberately sends it. Here are the three usual ways to call the mysql functions:

Calling the function without error handling. The function is called without any statements that provide error messages. For instance, the mysql_connect function can be called as follows:
$connection = mysql_connect($host,$user,$password);

If this statement fails (for instance, the account is not valid), the connection is not made, but the remaining statements in the program continue to execute. In most cases, this isn’t useful because some of the statements in the rest of the program might depend on having an open connection, such as getting or storing data in the database.

Calling the function with a die statement. The function is called with a die statement that sends a message to the browser. For instance, the mysql_connect function can be called as follows:
$connection = mysql_connect($host,$user,$password)
or die (“Couldn’t connect to server”);

If this statement fails, the connection is not made, and the die statement is executed. The die statement stops the program and sends the message to the browser. If the connection can’t be established, no more statements are executed. You can put any message that you want in the die statement.

Calling the function in an if statement. The function is called by using an if statement that executes a block of statements if the connection fails. For instance, the mysql_connect function can be called as follows:
if (!$connection = mysql_connect($host,$user,$password))
{
$message = mysql_error(); echo “$message<br>”; die();
}

If this statement fails, the statements in the if block are executed. The mysql_error func­ tion returns the MySQL error message and saves it in the variable $message. The error mes­ sage is then echoed. The die statement ends the program so that no more statements are executed. Notice the ! (exclamation point) in the if statement. ! means “not”. In other words, the if statement is true if the assignment statement is not true.

What error handling you want to include in your program depends on what you expect to happen in the program. When you’re developing the program, you expect some errors to happen. Therefore, during development, you probably want error handling that is more descriptive, such as the third

method in the preceding list. For instance, suppose that you’re using an account called root to access your database and that you make a typo as in the following statements:
$host = “localhost”;
$user = “rot”;
$password = “”;
if (!$connection = mysql_connect($host,$user,$password))
{
$message = mysql_error(); echo “$message<br>”; die();
}

Because you typed “rot” instead of “root”, you would see an error message similar to the following one:
Access denied for user: ‘rot@localhost’ (Using password: NO)

This error message has the information that you need to figure out what the problem is; it shows your account name with the typo. However, after your program is running and customers are using it, you probably don’t want your users to see a technical error message like the preceding one. Instead, you probably want to use the second method with a general statement in the die message, such as The Pet Catalog is not available at the moment. Please try again later.

Fill in the following information:

addr: The name of the computer where MySQL is installed — for example, databasehost.mycompany.com. If the MySQL database is on the same computer as your Web site, you can use localhost as the computer name. If this information is blank (“”), PHP assumes localhost.

mysqlacctname: The name of your MySQL account. (I discuss MySQL accounts in detail in Chapter 5.) You can leave this information blank (“”) — meaning that any account can connect — but this is usually a bad idea for security reasons.

password: The password for your MySQL account. If your MySQL account does not require a password, don’t type anything between the quotes: “”.

message: The message that is sent to the browser if the connection fails.
The connection fails if the computer or network is down or if the MySQL server isn’t running. It also can fail if the information provided isn’t correct — for example, if there’s a typo in the password.

You might want to use a descriptive message during development, such as Couldn’t connect to server, but use a more general message suit­ able for customers after the application is in use, such as The Pet Catalog is not available at the moment. Please try again later.

The addr includes a port number that is needed for the connection. Almost always, the port number is 3306. On rare occasions, the MySQL administrator needs to set up MySQL to connect on a different port. In these cases, the port number is required for the connection. The port number is specified as hostname:portnumber. For instance, you might use localhost:8808.

With these statements, mysql_connect attempts to open a connection to the named computer, using the account name and password provided. If the con­ nection fails, the program stops running at this point and sends message to the browser.

The following statement connects to the MySQL server on the local computer by using a MySQL account named catalog that does not require a password:

$connection = mysql_connect(“localhost”,”catalog”,””)
or die (“Couldn’t connect to server.”);

For security reasons, it’s a good idea to store the connection information in variables and use the variables in the connection statement, as follows:

$host=”localhost”;
$user=”catalog”;
$password=””;
$connection = mysql_connect($host,$user,$password)
or die (“Couldn’t connect to server.”);

In fact, for even more security, you can put the assignment statements for the connection information in a separate file in a hidden location so that the account name and password aren’t even in the program. I explain how to do this in Chapter 10.

The variable $connection contains information that identifies the connec­ tion. You can have more than one connection open at a time by using more than one variable name. A connection remains open until you close it or until the program ends. You close a connection as follows:

mysql_close($connectionname);

For instance, to close the connection in the preceding example, use this statement:

mysql_close($connection);

Selecting the right database

After the connection to the MySQL server is established and open, you need to tell MySQL which database you want to interact with. Use the mysql_select_db function as follows:

$db = mysql_select_db(“databasename”,$connectionname)
or die (“message”);

Fill in the following information:

databasename: The name of the database.

connectionname: The variable that contains the connection informa­ tion. If you don’t enter a connection, PHP uses the last connection that was opened.

message: The message that is sent to the browser if the database can’t be selected. The selection might fail because the database can’t be found, which is usually the result of a typo in the database name.

For instance, you can select the database PetCatalog with the following statement:

$db = mysql_select_db(“PetCatalog”,$connection)
or die (“Couldn’t select database.”);

If mysql_select_db is unable to select the database, the program stops run­ ning at this point, and the message Couldn’t select database. is sent to the browser.

For security reasons, it’s a good idea to store the database name in a variable and use the variable in the connection statement, as follows:

$database = “PetCatalog”;
$db = mysql_select_db($database,$connection)
or die (“Couldn’t select database.”);

In fact, for even more security, you can put the assignment statement for the database name in a separate file in a hidden location — as suggested for the assignment statements for the connection information — so that the data­ base name isn’t even in the program. I explain how to do this in Chapter 10.

The database stays selected until you explicitly select a different database. To select a different database, just use a new mysql_select_db function statement.

Sending SQL queries

After you have an open connection to the MySQL server and PHP knows which database you want to interact with, you send your SQL query. The quer y is a request to the MySQL server to store some data, update some data, or retrieve some data. (See Chapter 4 for more on the SQL language and how to build SQL queries.)

To interact with the database, put your SQL query into a variable and send it to the MySQL server by using the function mysql_query, as in the following example:

$query = “SELECT * FROM Pet”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

The query is executed on the currently selected database for the last connec­ tion that you opened. If you need to — if you have more than one connection open, for instance — you can send the query to a specific database server
like this:

$result = mysql_query($query,$connection)
or die (“Couldn’t execute query.”);

The variable $result holds information on the result of executing the query. The information depends on whether or not the query gets information
from the database:

For queries that don’t get any data: The variable $result contains information on whether the query executed successfully or not. If it’s successful, $result is set to TRUE; if it’s not successful, $result is set to FALSE. Some queries that don’t return data are INSERT and UPDATE.

For queries that return data: The variable $result contains a result identifier that identifies where the returned data is located and not the returned data itself. Some queries that do return data are SELECT and SHOW.

The use of single and double quotes can be a little confusing when assigning the query string to $query. You are actually using quotes on two levels: the quotes needed to assign the string to $query and the quotes that are part of the SQL language query itself. The following rules will help you avoid any problems with quotes:

Use double quotes at the beginning and end of the string.

Use single quotes before and after variable names.

Use single quotes before and after any literal values.

The following are examples of assigning query strings:

$query = “SELECT firstName FROM Member”;
$query = “SELECT firstName FROM Member WHERE lastName=’Smith’”;
$query = “UPDATE Member SET lastName=’$last_name’”;

The query string itself does not include a semicolon (;), so don’t put a semi­ colon inside the final quote. The only semicolon is at the very end; this is the PHP semicolon that ends the statement.

Getting Information from a Database

Getting information from a database is a common task for Web database applications. Here are two common uses for information from the database:

Use the information to conditionally execute statements. For instance, you might get the state of residence from the Member Directory and send different messages to members who live in different states.

Display the information in a Web page. For instance, you might want to display product information from your database.

In order to use the database information in a program, you need to put the information in variables. Then you can use the variables in conditional state­ ments, echo statements, or other statements. Getting information from a database is a two-step process:

1. You build a SELECT query and send the query to the database. When the query is executed, the selected data is stored in a temporary location.

2. You move the data from the temporary location into variables and use it in your program.

Sending a SELECT query

You use the SELECT query to get data from the database. SELECT queries are written in the SQL language. (I discuss the SELECT query in detail in Chapter 4.)

To get data from the database, build the SELECT query that you need, storing it in a variable, and then send the query to the database. The following statements select all the information from the Pet table in the PetCatalog database:

$query = “SELECT * FROM Pet”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

The mysql_query function gets the data requested by the SELECT query and stores it in a temporary location. You can think of this data as being stored in a table, similar to a MySQL table, with the information in rows and columns.

The function returns a result identifier that contains the information needed to find the temporary location where the data is stored. In the preceding statements, the result identifier is put into the variable $result. The next step after executing the function is to move the data from its temporary loca­ tion into variables that can be used in the program.

If the function fails — for instance, if the query is incorrect — $result
contains FALSE.

Getting and using the data

You use the mysql_fetch_array function to get the data from the temporary location. The function gets one row of data from the temporary location. The temporary data table might contain only one row of data or, more likely, your select query resulted in more than one row of data in the temporary data table. If you need to fetch more than one row of data from the temporary location, you use the mysql_fetch_array function in a loop.

Getting one row of data
To move the data from its temporary location and put it into variables that you can use in your program, you use the PHP function mysql_fetch_array. The general format for the mysql_fetch_array function is

$row = mysql_fetch_array($resultidentifier,typeofarray);

This statement gets one row from the data table in the temporary location and puts it in an array variable called $row. Fill in the following information:

resultidentifier: The variable that points to the temporary location of the results.

typeofarray: The type of array that the results are put into. It can be one of two types of arrays or both types. Use one of the following values:

• MYSQL_NUM: An array with a key/value pair for each column in the row using numbers as keys.

• MYSQL_ASSOC: An array with a key/value pair for each column in the row using the column names as keys.

• MYSQL_BOTH: An array with both types of keys. In other words, the array has two key/value pairs for each column: one with a number as the key and one with the column name as the key. If no array type is given in the function call, MYSQL_BOTH is assumed.

The mysql_fetch_array function gets one row of data from the temporary location. In some cases, one row is all you selected. For instance, to check the password entered by a user, you only need to get the user’s password from the database and compare it with the password that the user entered. The following statements check a password:

$userEntry = “secret”; // password user entered in form
$query = “SELECT password FROM Member
WHERE loginName=’gsmith’”;
$result = mysql_query($query)

Chapter 8: Data In, Data Out 199

or die (“Couldn’t execute query.”);
$row = mysql_fetch_array($result,MYSQL_ASSOC);
if ( $userEntry == $row[‘password’] )
{

}
else
{

}

echo “Login accepted<br>”;
statements that display Members Only Web pages

echo “Invalid password<br>”;
statements that allow user to try another password

Note the following points about the preceding statements:

The SELECT query requests only one field (password) from one row (row for gsmith).

The mysql_fetch_array function returns an array called $row with
column names as keys.

The if statement compares the password that the user typed in ($userEntry) with the password obtained from the database ($row[‘password’]) to see whether they are the same by using two equal signs (==).

If the comparison is true, the passwords match, and the if block (which displays the Members Only Web pages) is executed.

If the comparison is not true, the user did not enter a password that matches the password stored in the database, and the else block is exe­ cuted. The user sees an error message stating that the password is not correct and is returned to the login Web page.

PHP provides a shortcut that is convenient for using the variables retrieved with the mysql_fetch_array function. You can use the extract function, which splits the array into variables that have the same name as the key. For instance, you can use the extract function to rewrite the previous state­ ments that test the password. Here’s how:

$userEntry = “secret”; #password user entered into HTML form
$query = “SELECT password FROM Member
WHERE loginName=’gsmith’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);
$row = mysql_fetch_array($result,MYSQL_ASSOC);
extract($row);
if ( $userEntry == $password )
{

}
else

echo “Login accepted<br>”;
statements that display Members Only Web pages

{
echo “Invalid password<br>”;
statements that allow user to try another password
}

Using a loop to get all the rows of data
If you selected more than one row of data, use a loop to get all the rows from the temporary location. The loop statements in the loop block get one row of data and process it. The loop repeats until all rows have been retrieved. You can use a while loop or a for loop to retrieve this information. (For more on while loops and for loops, check out Chapter 7.)

The most common way to process the information is to use a while loop as follows:

while ( $row = mysql_fetch_array($result))
{
block of statements
}

This loop repeats until it has fetched the last row. If you just want to echo all the data, for example, you would use a loop similar to the following:

while ( $row = mysql_fetch_array($result))
{
extract($row);
echo “$petType: $petName<br>”;
}

Now, take a look at an example of how to get information for the Pet Catalog application. Assume the Pet Catalog has a table called Pet with four columns: petID, petType, petDescription, and price. Table 8-1 shows a sample set of data in the Pet table.

The petDisplay.php program in Listing 8-1 selects all the horses from the Pet table and displays the information in an HTML table in the Web page. The variable $pettype contains information that a user typed into a form.

Listing 8-1: Displays Items from the Pet Catalog

<?php
/* Program: petDisplay.php
* Desc: Displays all pets in selected category.
*/
?>
<html>
<head><title>Pet Catalog</title></head>
<body>
<?php
$user=”catalog”;
$host=”localhost”;
$password=””;
$database = “PetCatalog”;
$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);
$db = mysql_select_db($database,$connection)
or die (“Couldn’t select database”);
$pettype = “horse”; //horse was typed in a form by user
$query = “SELECT * FROM Pet WHERE petType=’$pettype’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

/* Display results in a table */
$pettype = ucfirst($pettype).”s”;
echo “<h1>$pettype</h1>”;
echo “<table cellspacing=’15’>”;
echo “<tr><td colspan=’3’><hr></td></tr>”;
while ($row = mysql_fetch_array($result))
{
extract($row);
$f_price = number_format($price,2);
echo “<tr>\n
<td>$petName</td>\n
<td>$petDescription</td>\n
<td align=’right’>\$$f_price</td>\n
</tr>\n”;
echo “<tr><td colspan=’3’><hr></td></tr>\n”;
}
echo “</table>\n”;
?>
</body></html>

Figure 8-1 shows the Web page displayed by the program in Listing 8-1. The Web page shows the Pet items for the petType horse, with the display for­ matted in an HTML table.

The program in Listing 8-1 uses a while loop to get all the rows from the temporary location. In some cases, you might need to use a for loop. For instance, if you need to use a number in your loop, a for loop is more useful than a while loop.

To use a for loop, you need to know how many rows of data were selected. You can find out how many rows are in the temporary storage by using the PHP function mysql_num_rows as follows:

$nrows = mysql_num_rows($result);

The variable $nrows contains the number of rows in the temporary storage location. By using this number, you can build a for loop to get all the rows, as follows:

for ($i=0;$i<$nrows;$i++)
{
$row = mysql_fetch_array($result))
block of statements;
}

For instance, the program in Listing 8-1 displays the Pet items of the type horse. Suppose that you want to number each item. Listing 8-2 shows a pro­ gram, petDescripFor.php, which displays a numbered list by using a for loop.

Listing 8-2: Displays Numbered List of Items from the Pet Catalog

<?php
/* Program: petDescripFor.php
* Desc: Displays a numbered list of all pets in
* selected category.
*/
?>
<html>
<head><title>Pet Catalog</title></head>
<body>
<?php
$user=”catalog”;
$host=”localhost”;
$password=””;
$database = “PetCatalog”;
$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);
$db = mysql_select_db($database,$connection)
or die (“Couldn’t select database”);
$pettype = “horse”; //horse was typed in a form by user
$query = “SELECT * FROM Pet WHERE petType=’$pettype’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);
$nrows = mysql_num_rows($result);

/* Display results in a table */
echo “<h1>Horses</h1>”;
echo “<table cellspacing=’15’>”;
echo “<tr><td colspan=’4’><hr></td></tr>”;
for ($i=0;$i<$nrows;$i++)
{
$n = $i + 1; #add 1 so that numbers don’t start with 0
$row = mysql_fetch_array($result);
extract($row);
$f_price = number_format($price,2);
echo “<tr>\n
<td>$n.</td>\n
<td>$petName</td>\n
<td>$petDescription</td>\n
<td align=’right’>\$$f_price</td>\n
</tr>\n”;
echo “<tr><td colspan=’4’><hr></td></tr>\n”;
}
echo “</table>\n”;
?>
</body></html>

Figure 8-2 shows the Web page that results from using the for loop in this program. Notice that a number appears before the listing for each Pet item on this Web page.

Using functions to get data

In most applications, you get data from the database. Often you get the data in more than one location in your program or more than one program in your application. Functions — blocks of statements that perform certain specified tasks — are designed for such situations. (I explain functions in detail in Chapter 7.)

A function to get data from the database can be really useful. Whenever the program needs to get data, you call the function. Not only do functions save you a lot of typing, but they also make the program easier for you to follow.

For example, consider a product catalog, such as the Pet Catalog. You will need to get information about a specific product many times. You can write a function that gets the data and then use that function whenever you need data.

Listing 8-3 for program getdata.php shows how to use a function to get data. The function in Listing 8-3 will get the information for any single pet in the Pet Catalog. The pet information is put into an array, and the array is returned to the main program. The main program can then use the informa­ tion any way that it wants. In this case, it echoes the pet information to a Web page.

<?php
/* Program: getdata.php
* Desc: Gets data from a database using a function
*/
?>
<html>
<head><title>Pet Catalog</title></head>
<body>
<?php
$user=”catalog”;
$host=”localhost”;
$password=””;
$connection = mysql_connect($host,$user,$password)
or die (“Couldn’t connect to server”);

$petInfo = getPetInfo(“Unicorn”); //call function

$f_price = number_format($petInfo[‘price’],2);
echo “<p><b>{$petInfo[‘petName’]}</b><br>\n Description: {$petInfo[‘petDescription’]}<br>\n Price: \${$petInfo[‘price’]}\n”
?>
</body></html>

<?php
function getPetInfo($petName)
{
$db = mysql_select_db(“PetCatalog”)
or die (“Couldn’t select database”);
$query = “SELECT * FROM Pet WHERE petName=’$petName’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);
return mysql_fetch_array($result,MYSQL_ASSOC);
}
?>

The Web page displays

Unicorn
Description: spiral horn centered in forehead
Price: $10,000.00

Notice the following about the program in Listing 8-3:

The program is easier to read with the function call than it would be if all the function statements were in the main program.

You can connect to the MySQL server once in the main program and call the function many times to get data. If the connection were in the

function rather than the main program, it would connect every time that you called the function. It’s more efficient to connect only once, if possible.

If you only have one connection, mysql_select_db will use that con­ nection. If you have more than one connection, you can pass the connection and use it in your mysql_select_db function call. If your application only uses one database, you can select that database once in the main program instead of selecting it in the function.

The function call sends the string “Unicorn”. In most cases, the func­
tion call will use a variable name.

The program creates the variable $petInfo to receive the data from the function. $petInfo is an array because the information stored in it is an array.

The preceding function is very simple — it returns one row of the results as an array. But functions can be more complex. The preceding section provides a program to get all the pets of a specified type. The program getPets.php
in Listing 8-4 uses a function for the same purpose. The function returns a multidimensional array with the pet data for all the pets of the specified type.

Listing 8-4: Displays Numbered List of Pets by Using a Function

<?php
/* Program: getPets.php
* Desc: Displays numbered list of items from a database.
*/
?>
<html>
<head><title>Pet Catalog</title></head>
<body>
<?php
$user=”catalog”;
$host=”localhost”;
$password=””;
$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);

$petInfo = getPetsOfType(“horse”); //call function

/* Display results in a table */
echo “<h1>Horses</h1>”;
echo “<table cellspacing=’15’>”;
echo “<tr><td colspan=’4’><hr></td></tr>”;
for ($i=1;$i<=sizeof($petInfo);$i++)
{
$f_price = number_format($petInfo[$i][‘price’],2);
echo “<tr>\n
<td>$i.</td>\n
<td>{$petInfo[$i][‘petName’]}</td>\n
<td>{$petInfo[$i][‘petDescription’]}</td>\n
<td align=’right’>\$$f_price</td>\n
</tr>\n”;
echo “<tr><td colspan=’4’><hr></td></tr>\n”;
}
echo “</table>\n”;
?>
</body></html>

<?php
function getPetsOfType($petType)
{
$db = mysql_select_db(“PetCatalog”)
or die (“Couldn’t select database”);
$query = “SELECT * FROM Pet WHERE petType=’$petType’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

$j = 1;
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
foreach ($row as $colname => $value)
{
$array[$j][$colname] = $value;
}
$j++;
}
return $array;
}
?>

The program in Listing 8-4 proceeds as follows:

1. It connects to the MySQL server in the main program.

2. It calls the function getPetsOfType. It passes “horse” as a character string and also sets up $petInfo to receive the data returned by the function.

3. The function selects the database PetCatalog.

4. The function sends a query to get all the rows with horse in the petType column. The data is stored in a table in a temporary location. The variable $result identifies the location of the temporary table.

5. It sets up a counter. $j is a counter that is incremented in each loop. It starts at 1 before the loop.

6. It starts a while loop. The function attempts to get a row from the tem­ porary data table and is successful. If there were no rows to get in the temporary location, the while loop would end.

7. It starts a foreach loop. The loop walks through the row, processing
each field.

8. It stores values in the array. $petInfo is a multidimensional array. Its first key is a number, which is set by the counter. Because this is the first time through the while loop, the counter — $j — is now equal to 1.
All the fields in the row are stored in $petInfo with the column name as the key. (I explain multidimensional arrays in detail in Chapter 7.)

9. It increments the counter. $j is incremented by 1.

10. It reaches the end of the while loop.

11. It returns to the top of the while loop.

12. It repeats Steps 6–11 for every row in the results.

13. It returns $array to the main program. $array contains all the data for all the selected rows.

14. $petInfo receives data from the function. All the data is passed.
Figure 8-3 shows the structure of $petInfo after the function has finished executing.

15. The main program sends Pet Descriptions to the browser in an HTML
table. The appropriate data is inserted from the $petInfo array.

The Web page that results from the program in Listing 8-4 is identical to the Web page shown in Figure 8-2, which is produced by a program that does not use a function. Functions do not produce different output. Any program that you can write by using a function, you can also write without using a func­ tion. Functions just make programming easier.

Getting Information from the User

Many applications are designed to ask questions that users answer by typing information. Sometimes the information is stored in a database; sometimes

the information is used in conditional statements to deliver an individual Web page. Some of the most common application tasks that require users to answer questions are

Online ordering: Customers need to select products and enter shipping and payment information.

Registering: Many sites require users to provide some information before they receive certain benefits, such as access to special informa­ tion or downloadable software.

Logging in: Many sites restrict access to their pages. Users must enter an account name and password before they can see the Web pages.

Viewing selected information: Many sites allow users to specify what information they want to see. For instance, an online catalog might allow users to type the name of the product or select a product category that they want to see.

You ask questions by displaying HTML forms. The user answers the ques­ tions by typing information into the form or selecting items from a list. The user then clicks a button to submit the form information. When the form is submitted, the information in the form is passed to a second, separate pro­ gram, which processes the information.

In the next few sections, I don’t tell you about the HTML required to display a form; I assume that you already know HTML. (If you don’t know HTML or need a refresher, check out HTML 4 For Dummies, 4th Edition, by Ed Tittel and Natanya Pitts; Wiley.) What I do tell you is how to use PHP to display HTML forms and to process the information that users type into the form.

Using HTML forms

HTML forms are very important for interactive Web sites. If you are unfamil­ iar with HTML forms, you need to read the forms section of an HTML book. To display a form by using PHP, you can do one of the following:

Use echo statements to echo the HTML for a form. For example:

<?php
echo “<form action=’processform.php’
method=’POST’>\n
<input type=’text’ name=’name’>\n
<input type=’submit’ value=’Submit Name’>\n
</form>\n”;
?>

210 Part III: PHP

Use plain HTML outside the PHP sections. For a plain static form, there is no reason to include it in a PHP section. For example:

<?php
statements in PHP section
?>
<form action=”processform.php” method=”POST”>
<input type=”text” name=”fullname”>
<input type=”submit” value=”Submit Name”>
</form>
<?php
statements in PHP section
?>

Either of these methods produces the form displayed in Figure 8-4.

Joe Customer fills in the HTML form. He clicks the submit button. You now have the information that you wanted — his name. So where is it? How do you get it?

You get the form information by running a program that receives the form information. When the submit button is clicked, PHP automatically runs a program. The action parameter in the form tag tells PHP which pro­ gram to run. For instance, in the preceding program, the parameter action=processform.php tells PHP to run the program processform.php
when the user clicks the submit button. The program processform.php can display, store, or otherwise use the form data that it receives when the form is submitted.

When the user clicks the submit button, the program specified in the action attribute runs, and statements in this program can get the form information from PHP built-in arrays and use the information in PHP statements. Table 8-2 shows the built-in arrays that contain the form information.

When the form is submitted, the program that runs can get the form informa­ tion from the appropriate built-in array, as shown in Table 8-2. In these built- in arrays, each array index is the name of the input field in the form. For
instance, if the user typed Goliath Smith in the input field shown in Figure 8-4 and clicked the submit button, the program processform.php runs and can use an array variable in the following format:

$_POST[‘fullname’]

Notice that the named typed into the form is available in the $_POST array because the form tag specified method=’POST’. Also, notice that the array key is the name given the field in the HTML form with the name attribute name=”fullname”.

A program that displays all the fields in a form is a useful program for testing a form. You can see what values are passed from the form to be sure that your form is formatted properly and sends the field names and values that
you expect. All the fields in a POST type form are displayed by the program in Listing 8-5, named processform.php. When the form shown in Figure 8-4 is submitted, the following program is run.

Listing 8-5: A Script That Displays All the Fields from a Form

<?php
/* Script name: processform.php
* Description: Script displays all the information passed
* from a form.
*/
echo “<html>
<head><title>Customer Address</title></head>
<body>”;

(continued)

Listing 8-5 (continued)

foreach ($_POST as $field => $value)
{
echo “$field = $value<br>”;
}
?>
</body></html>

If the user typed the name Goliath Smith into the form in Figure 8-4, the following output is displayed:

fullname = Goliath Smith

The output displays only one line because there is only one field in the form in Figure 8-4.

The program in Listing 8-5 is written to process the form information from any form that uses the POST method. Suppose that you have a slightly more complicated form, such as the program in Listing 8-6 that displays a form with several fields.

Listing 8-6: A Program That Displays an Address Form

<?php
/* Program name: displayForm
* Description: Script displays a form that asks for the
* customer address.
*/
echo “<html>
<head><title>Customer Address</title></head>
<body>”;
$labels = array( “firstName”=>”First Name:”, “midName”=>”Middle Name:”, “lastName”=>”Last Name:”, “street”=>”Street Address:”, “city”=>”City:”, “state”=>”State:”, “zip”=>”Zipcode:”);
echo “<p align=’center’>
<b>Please enter your address below.</b><hr>”;
echo “<form action=’processform.php’ method=’POST’>
<table width=’95%’ border=’0’ cellspacing=’0’
cellpadding=’2’>\n”;
foreach($labels as $field=>$label)
{
echo “<tr>
<td align=’right’> <B>{$labels[$field]} </br></td>
<td><input type=’text’ name=’$field’ size=’65’
maxlength=’65’ ></td>
</tr>”;

}
echo “</table>
<div align=’center’><p><input type=’submit’
value=’Submit Address’> </p></div>
</form>”;
?>
</body></html>

Notice the following in displayForm.php, as shown in Listing 8-6:

An array is created that contains the labels that are used in the form.
The keys are the field names.

The script processform.php is named as the script that runs when the form is submitted. The information in the form is sent to processform.php, which processes the information.

The form is formatted with an HTML table. Tables are an important part of HTML. If you’re not familiar with HTML tables, check out HTML 4
For Dummies, 4th Edition, by Ed Tittel and Natanya Pitts (Wiley).

The script loops through the $labels array with a foreach statement.
The HTML code for a table row is output in each loop. The appropriate array values are used in the HTML code.

For security reasons, always include maxlength — which defines the number of characters that users are allowed to type into the field — in your HTML statement. Limiting the number of characters helps prevent the bad guys
from typing malicious code into your form fields. If the information will be stored in a database, set maxlength to the same number as the width of the column in the database table.

When Goliath Smith fills in the form shown in Figure 8-5 (created by the pro­ gram in Listing 8-6) and submits it, the program processform.php runs and produces the following output:

firstName = Goliath midName =
lastName = Smith street = 1234 Tall St city = Big City
state = TX
zip = 88888

In processform.php, all elements of the $_POST built-in array are displayed because both of the forms shown in this section used the POST method, as do most forms. There are other built-in arrays, as well as the $_POST array, as shown in Table 8-2.

The same information is available in two sets of arrays. Use the newer arrays (names begin with _) because they can be used anywhere, even inside a function. (I explain functions and the use of variables inside functions in Chapter 7.) These arrays, called superglobals or autoglobals, were introduced in PHP 4.1.0. The older arrays, with long names such as $HTTP_POST_VARS, must be made global before they can be used in a function, as I explain in Chapter 7. The older arrays should only be used when you are forced to use
a version of PHP older than PHP 4.1.0.

Making forms dynamic

PHP brings new capabilities to HTML forms. Because you can use variables in PHP forms, your forms can now be dynamic. Here are the major capabilities that PHP brings to forms:

Using variables to display information in input text fields

Using variables to build dynamic lists for users to select from

Using variables to build dynamic lists of radio buttons

Using variables to build dynamic lists of check boxes

Displaying dynamic information in form fields
When you display a form on a Web page, you can put information into the fields rather than just displaying a blank field. For example, if most of your customers live in the United States, you might automatically enter US in the country field when you ask customers for their address. If the customer does

indeed live in the United States, you’ve saved the customer some typing. And if the customer doesn’t live in the U.S., he or she can just replace US with the appropriate country. Also, if the program automatically enters US as the value in the field, you know that the information doesn’t have any errors in it.

To display a text field that contains information, you use the following format for the input field HTML statements:

<input type=”text” name=”country” value=”US”>

By using PHP, you can use a variable to display this information with either of the following statements:

<input type=”text” name=”country”
value=”<?php echo $country ?>”>
echo “<input type=’text’ name=’country’ value=’$country’>”;

The first example creates an input field in an HTML section, using a short PHP section for the value only. The second example creates an input field by using an echo statement inside a PHP section. If you’re using a long form with only an occasional variable, using the first format is more efficient. If your form uses many variables, it’s more efficient to use the second format.

If you have user information stored in a database, you might want to display the information from the database in the form fields. For instance, you might show the information to the user so that he or she can make any needed changes. Or you might display the shipping address for the customer’s last online order so that he or she doesn’t need to retype the address. Listing 8-7 shows the program displayAddress.php, which displays a form with infor­ mation from the database. This form is very similar to the form shown in Figure 8-5 except that this form has information in it (retrieved from the data­ base) and the fields in the form in Figure 8-5 are blank.

Registering long arrays

A new php.ini setting introduced in PHP 5 allows you to prevent the older, long arrays from being created automatically by PHP. It’s very unlikely that you will need to use them unless you’re using some old scripts containing the long variables. The following line in php.ini controls this setting:
register_long_arrays = On

At the current time, this setting is On by default. Unless you’re running old scripts that need the

old arrays, you should change the setting to
Off so that PHP doesn’t do this extra work.

Although the setting is currently On by default, that could change. The default setting might change to Off in a future version. If you’re using some old scripts and are getting errors on lines containing the long arrays, such as
$HTTP_GET_VARS, check your php.ini set- ting for long arrays. It might be Off, and the long arrays needed by the older script are not being created at all.

Listing 8-7: Program to Display HTML Form with Information

<?php
/* Program name: displayAddress
* Description: Script displays a form with address
* information obtained from the database.
*/
echo “<html>
<head><title>Customer Address</title></head>
<body>”;
$labels = array( “firstName”=>”First Name:”, “lastName”=>”Last Name:”, “street”=>”Street Address:”, “city”=>”City:”, “state”=>”State:”, “zip”=>”Zipcode:”);
$user=”admin”;
$host=”localhost”;
$password=””;
$database = “MemberDirectory”;
$loginName = “gsmith”; // user login name

$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);
$db = mysql_select_db($database,$connection)
or die (“Couldn’t select database”);
$query = “SELECT * FROM Member
WHERE loginName=’$loginName’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);
$row = mysql_fetch_array($result);

echo “<p align=’center’>
<h1 align=’center’>Address for $loginName</h1>\n”;
echo “<br><p align=’center’>
<font size=’+1’><b>Please check the information below and change any information that is incorrect.</b></font>
<hr>”;
echo “<form action=’processAddress.php’ method=’POST’>
<table width=’95%’ border=’0’ cellspacing=’0’
cellpadding=’2’>\n”;
foreach($labels as $field=>$label)
{
echo “<tr>
<td align=’right’> <B>{$labels[$field]} </br></td>
<td><input type=’text’ name=’$field’
value=’$row[$field]’ size=’65’ maxlength=’65’>
</td>
</tr>”;
}
echo “</table>
<div align=’center’><p><input type=’submit’
value=’Submit Address’> </p></div>
</form>”;
?>
</body></html>

Notice the following in the program in Listing 8-7:

The form statement transfers the action to the program processAddress.php. This program processes the information in the form and updates the database with any information that the user changed. This is a program that you write yourself. Checking data in a form and saving information in the database are discussed later in this chapter in the sections “Checking the information” and “Putting Information into a Database”.

Each input field in the form is given a name. The information in the input field is stored in a variable that has the same name as the input field.

The program gives the field names in the form the same names as the columns in the database. This simplifies moving information between the database and the form, requiring no transfer of information from one variable to another.

The values from the database are displayed in the form fields with the value parameter in the input field statement. The value parameter displays the appropriate value from the array $row, which contains data from the database.

For security reasons, always include maxlength in your HTML statement. maxlength defines the number of characters that a user is allowed to type into the field. If the information is going to be stored in a database, set maxlength to the same number as the width of the column in the database table.

Figure 8-6 shows the Web page resulting from the program in Listing 8-7. The information in the form is the information that is stored in the database.

Building selection lists
One type of field that you can use in an HTML form is a selection list. Instead of typing into a field, your users select from a list. For instance, in a product catalog, you might provide a list of categories from which users select what they want to view. Or the form for users’ addresses might include a list of states that users can select. Or users might enter a date by selecting a month, day, and year from a list.

Use selection lists whenever feasible. When the user selects an item from a list, you can be sure that the item is accurate, with no misspelling, odd char­ acters, or other problems introduced by users’ typing errors.

An HTML selection list for the categories in the Pet Catalog is formatted as follows:

<form action=”processform.php” method=”POST”>
<select name=”petType”>
<option value=”horse”>horse
<option value=”cat” selected>cat
<option value=”dragon”>dragon
</select> &nbsp;&nbsp;&nbsp;
<input type=”submit” value=”Select Type of Pet”>
</form>;

Figure 8-7 shows the selection list that these HTML statements produce. Notice that cat is the choice that is selected when the field is first displayed. You determine this default selection by including selected in the option tag.

When the user clicks the arrow on the select drop-down list box, the whole list drops down, as shown in Figure 8-8, and the user can select any item in the list. Notice that cat is selected until the user selects a different item.

When using PHP, your options can be variables. This capability allows you to build dynamic selection lists. For instance, you must maintain the static list of pet categories shown in the preceding example. If you add a new pet cate­
gory, you must add an option tag manually. However, with PHP variables, you can build the list dynamically from the categories in the database. When you add a new category to the database, the new category is automatically added to your selection list without your having to change your PHP program. Listing 8-8 for program buildSelect.php builds a selection list of pet cate­ gories from the database.

Listing 8-8: Program to Build a Selection List

<?php
/* Program name: buildSelect.php
* Description: Program builds a selection list
* from the database.
*/
?>
<html>
<head><title>Pet Types</title></head>
<body>
<?php
$user=”catalog”;
$host=”localhost”;
$password=””;
$database = “PetCatalog”;

$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);
$db = mysql_select_db($database,$connection)

or die (“Couldn’t select database”);
$query = “SELECT DISTINCT petType FROM Pet ORDER BY petType”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

/* create form containing selection list */
echo “<form action=’processform.php’ method=’POST’>
<select name=’petType’>\n”;

while ($row = mysql_fetch_array($result))
{
extract($row);
echo “<option value=’$petType’>$petType\n”;
}
echo “</select>\n”;
echo “<input type=’submit’ value=’Select Type of Pet’>
</form>\n”;
?>
</body></html>

Notice the following in the program in Listing 8-8:

Using DISTINCT in the query: DISTINCT causes the query to get each pet type only once. Without DISTINCT, the query would return each pet type several times if it appeared several times in the database.

Using ORDER BY in the query: The pet types are sorted alphabetically.

echo statements before the loop: The form and select tags are echoed before the while loop starts because they are echoed only once.

echo statements in the loop: The option tags are echoed in the loop — one for each pet type in the database. No item is marked as selected, so the first item in the list is selected automatically.

echo statements after the loop: The end form and select tags are
echoed after the loop because they are echoed only once.

The selection list produced by this program is initially the same as the selec­ tion list shown in Figure 8-7, with cat selected. However, cat is selected in this program because it is the first item in the list — not because it’s specifically selected as it is in the HTML tags that produce Figure 8-7. The drop-down list produced by this program is in alphabetical order, as shown in Figure 8-9.

You can also use PHP variables to set up which option is selected when the selection box is displayed. For instance, suppose that you want the user to select a date from month, day, and year selection lists. You believe that
most people will select today’s date, so you want today’s date to be selected by default when the box is displayed. Listing 8-9 shows the program dateSelect.php, which displays a form for selecting a date and selects today’s date automatically.
<?php
/* Program name: dateSelect.php
* Description: Program displays a selection list that
* customers can use to select a date.
*/
echo “<html>
<head><title>Select a date</title></head>
<body>”;

/* create an array of months*/
$monthName = array(1=> “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”);

$today = time(); //stores today’s date
$f_today = date(“M-d-Y”,$today); //formats today’s date

echo “<div align=’center’>\n”;

/* display today’s date */
echo “<p>&nbsp;<h3>Today is $f_today</h3><hr>\n”;

/* create form containing date selection list */
echo “<form action=’processform.php’ method=’POST’>\n”;

/* build selection list for the month */
$todayMO = date(“m”,$today); //get the month from $today echo “<select name=’dateMO’>\n”;
for ($n=1;$n<=12;$n++)
{

echo “<option value=$n\n”;
if ($todayMO == $n)
{

(continued)

Listing 8-9 (continued)

echo “ selected”;
}
echo “> $monthName[$n]\n”;
}
echo “</select>”;

/* build selection list for the day */
$todayDay= date(“d”,$today); //get the day from $today echo “<select name=’dateDay’>\n”;
for ($n=1;$n<=31;$n++)
{
echo “ <option value=$n”;
if ($todayDay == $n )
{
echo “ selected”;
}
echo “> $n\n”;
}
echo “</select>\n”;

/* build selection list for the year */
$startYr = date(“Y”, $today); //get the year from $today echo “<select name=’dateYr’>\n”;
for ($n=$startYr;$n<=$startYr+3;$n++)
{
echo “ <option value=$n”;
if ($startYr == $n )
{
echo “ selected”;
}
echo “> $n\n”;
}
echo “</select>\n”;
echo “</form>\n”;
?>
</body></html>

The Web page produced by the program in Listing 8-9 is shown in Figure 8-10. The date appears above the form so that you can see that the select list shows the correct date. The selection list for the month shows all 12 months when it drops down. The selection list for the day shows 31 days when it drops down. The selection list for year shows four years.

The program in Listing 8-9 produces the Web page in Figure 8-10 by following these steps:

1. Creates an array containing the names of the months. The keys for the array are the numbers. The first month, January, starts with the key 1 so that the keys of the array match the numbers of the months.
2. Creates variables containing the current date. $today contains the
date in a system format and is used in the form. $f-today is a formatted date that is used to display the date in the Web page.

3. Displays the current date at the top of the Web page.

4. Builds the selection field for the month.

i. Creates a variable containing today’s month.

ii. Echoes the select tag, which should be echoed only once. iii. Starts a for loop that repeats 12 times.
iv. Inside the loop, echoes the option tag by using the first value from the $monthName array.

v. If the number of the month being processed is equal to the number of the current month, adds the word “selected” to the option tag.

vi. Repeats the loop 11 more times.

vii. Echoes the closing select tag for the selection field, which should be echoed only once.

5. Builds the selection field for the day. Uses the procedure described in Step 4 for the month. However, only numbers are used for this selection list. The loop repeats 31 times.

6. Builds the selection field for the year.

i. Creates the variable $startYr, containing today’s year.

ii. Echoes the select tag, which should be echoed only once.

iii. Starts a for loop. The starting value for the loop is $startYr. The ending value for the loop is $startYr+3.

iv. Inside the loop, echoes the option tag, using the starting value of the for loop, which is today’s year.

v. If the number of the year being processed is equal to the number
of the current month, adds the word “selected” to the option tag. vi. Repeats the loop until the ending value equals $startYr+3.
vii. Echoes the closing select tag for the selection field, which should be echoed only once.

7. Echoes the ending tag for the form.

Building lists of radio buttons
You might want to use radio buttons instead of selection lists. For instance, you can display a list of radio buttons for your Pet Catalog and have users select the button for the pet category that they’re interested in.

The format for radio buttons in forms is

<input type=”radio” name=”pets” value=”Unicorn”>

You can build a dynamic list of radio buttons representing all the pet types in your database in the same manner that you build a dynamic selection list in the preceding section. Listing 8-10 shows the program buildRadio.php, which creates a list of radio buttons based on pet types.

Listing 8-10: Program to Build a List of Radio Buttons

<?php
/* Program name: buildRadio.php
* Description: Program displays a list of radio
* buttons from database info.
*/
echo “<html>
<head><title>Pet Types</title></head>
<body>”;
$user=”catalog”;
$host=”localhost”;
$password=””;
$database = “PetCatalog”;

$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);
$db = mysql_select_db($database,$connection)
or die (“Couldn’t select database”);
$query = “SELECT DISTINCT petType FROM Pet
ORDER BY petType”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

echo “<div style=’margin-left: .5in’>
<p>&nbsp;
<p><b>Which type of pet are you interested in?</b>
<p>Please choose one type of pet from the following list:\n”;
/* create form containing radio buttons */
echo “<form action=’processform.php’ method=’POST’>\n”;

while ($row = mysql_fetch_array($result))
{
extract($row);
echo “<input type=’radio’ name=’interest’
value=’$petType’>$petType\n”;
echo “<br>\n”;
}
echo “<p><input type=’submit’ value=’Select Type of Pet’>
</form>\n”;
?>
</div></body></html>

This program is very similar to the program in Listing 8-9. The Web page pro­
duced by this program is shown in Figure 8-11.
Building lists of check boxes
You might want to use check boxes in your form. Check boxes are different from selection lists and radio buttons because they allow users to select more than one option. For instance, if you display a list of pet categories by
using check boxes, a user can check two or three or more pet categories. The program buildCheckbox.php in Listing 8-11 creates a list of check boxes.
Using the information from the form

As I discuss earlier in this section, Joe Customer fills in an HTML form, selecting from lists and typing information into text fields. He clicks the submit button.

In the form tag, you tell PHP which program to run when the submit button is clicked. You do this by including action=”programname” in the form tag. For instance, in most of the example listings in this chapter, I use action=”processform.php”. When the user clicks the submit button,
the program runs and receives the information from the form. Handling form information is one of PHP’s best features. You don’t need to worry about the form data — just get it from one of the built-in arrays and use it.

The form data is available in the processing program in arrays, as shown in Table 8-1. The key for the array element is the name of the input field in the form. For instance, if you echo the following field in your form

echo “<input type=’text’ name=’firstName’>”;

the processing program can use the variable $_POST[firstName], which contains the text that the user typed into the field. The information that the user selects from selection drop-down lists or radio buttons is similarly avail­ able for use. For instance, if your form includes the following list of radio buttons

echo “<input type=’radio’ name=’interest’ value=’dog’>dog\n”;
echo “<input type=’radio’ name=’interest’ value=’cat’>cat\n”;

you can access the variable $_POST[interest], which contains either dog or
cat, depending on what the user selected.

You handle check boxes in a slightly different way because the user can select more than one check box. As shown in Listing 8-11, the data from a list of check boxes can be stored in an array so that all the check boxes are avail­ able. For instance, if your form includes the following list of check boxes

echo “<input type=’checkbox’ name=’interest[dog]’
value=’dog’>dog\n”;
echo “<input type=’checkbox’ name=’interest[cat]’
value=’cat’>cat\n”;

you can access the data by using the multidimensional variable
$_POST[interest], which contains the following:

$_POST[interest][dog] = dog
$_POST[interest][cat] = cat

In some cases, you might want to access all the fields in the form. Perhaps you want to check them all to make sure that the user didn’t leave any fields blank. As shown in program processform.php, earlier in this chapter (see Listing
8-5), you can use foreach to walk through the $_POST or $_GET built-in array. Most of the sample programs and statements in this book use the post method. The keys are the field names. See the sidebar “Post versus get” for more on the two methods.

For instance, suppose your program includes the following statements to dis­
play a form:

echo “<form action=’processform.php’ method=’POST’>\n”;
echo “<input type=’text’ name=’lname’ value=’Smith’><br>\n”; echo “<input type=’radio’ name=’interest’ value=’dog’>dog\n”; echo “<input type=’radio’ name=’interest’ value=’cat’>cat\n”; echo “<input type=’hidden’ name=’hidvar’ value=’3’>\n”;
echo “<br><input type=’submit’ value=’Select Type of Pet’>
</form>\n”;

The program processform.php contains the following statements that will list all the variables received from the form:

foreach ($_POST as $field => $value)
{

echo “$field, $value<br>”;
}

The output from the foreach loop would be

lname, Smith interest, dog hidvar, 3

The output shows three variables with these three values for the following reasons:

The user didn’t change the text in the text field. The value “Smith”
that the program displayed is still the text in the text field.

The user selected the radio button for dog. The user can select only one radio button.

The program passed a hidden field named hidvar. The program sets the value for hidden fields. The user can’t affect the hidden fields.

Post versus get

You use one of two methods to submit form information. The methods pass the form data differently and have different advantages and disadvantages.

get method: The form data is passed by adding it to the URL that calls the form- processing program. For instance, the URL might look like this:
processform.php?lname=Smith&
fname=Goliath

The advantages of this method are simplicity and speed. The disadvantages are that less data can be passed and that the information is displayed in the browser, which can be a security problem in some situations.

post method: The form data is passed as a package in a separate communication with

the processing program. The advantages of this method are unlimited information pass­ ing and security of the data. The disadvan­ tages are the additional overhead and slower speed.

For CGI programs that are not PHP, the program that processes the form must find the informa­ tion and put the data into variables. In this case, the get method is much simpler and easier to use. Many programmers use the get method for this reason. However, PHP does all this work for you. The get and post methods are equally easy to use in PHP programs. Therefore, when using PHP, it’s almost always better to use the post method because you have the advan­ tages of the post method (unlimited data pass­ ing, better security) without its main disadvan­ tage (more difficult to use).

Checking the information

Joe Customer fills in an HTML form, selecting from lists and typing informa­ tion into text fields. He clicks the submit button. You now have all the infor­ mation that you wanted. Well, maybe. Joe might have typed information that has a typo in it. Or he might have typed nonsense. Or he might even have typed in malicious information that can cause problems for you or for other people using your Web site. Before you use Joe’s information or store it in your database, you want to check it to see that it is the information that you asked for. Checking the data is validating the data.

Validating the data includes the following:

Checking for empty fields: You can require users to enter information in a field. If the field is blank, the user is told that the information is required, and the form is displayed again so the user can type the miss­ ing information.

Checking the format of the information: You can check the information to see that it is in the correct format. For instance, ab3&*xx is clearly
not a valid ZIP code.

Checking for empty fields
When you create a form, you can decide which fields are required and which are optional. Your decision is implemented in the PHP program. You check the fields that are required for information. If a required field is blank, you send a message to the user, indicating the field is required, and you then redisplay the form.

The general format to check for empty fields is

if ($last_name == “”)
{
echo “You did not enter your last name.
Last name is required.<br>\n”;
display the form;
exit();
}
echo “ Welcome to the Members Only club.
You may select from the menu below.<br>\n”;
display the menu;

Notice the exit statement. exit statements end the program. Without the exit statement, the program would continue to the statements after the if statement. In other words, without the exit statement, the program would display the form and then continue to echo the welcome statement and the menu as well.

In many cases, you want to check all the fields in the form. You can do this by looping through the array $ _POST. The following statements check the array for any empty fields:

foreach ($_POST as $value)
{
if ( $value == “” )
{
echo “You have not filled in all the fields<br>\n”;
display the form;
exit();
}
}
echo “Welcome”;

When you redisplay the Web form, make sure that it contains the information that the user already typed. If users have to retype information, they are likely to get frustrated and leave your Web site.

In some cases, you might require the user to fill in most of the fields but not all of them. For instance, you might request a fax number in the form or pro­ vide a field for a middle name, but you don’t really mean to restrict registra­ tion on your Web site to only users with middle names and faxes. In this case, you can just make an exception for the fields that are not required, as follows:

foreach ($_POST as $field => $value)
{
if ( $field != “fax” and $field != “middle_name” )
{
if ( $value == “” )
{
echo “You have not filled in all the fields<br>\n”;
display the form;
exit();
}
}
}
echo “Welcome”;

Notice that the outside if conditional statement is true only if the field is not the fax field and is not the middle name field. For those two fields, the pro­ gram does not reach the inside if statement, which checks for blank fields.

In some cases, you might want to tell the user exactly which fields need to be filled in. The checkBlank.php program in Listing 8-12 processes a form with four fields: first_name, middle_name, last_name, and phone. All the fields are required except middle_name. In the example shown in Figure 8-13, the user didn’t enter a first name: The resulting error message when the form is processed tells the user which field was left blank.

Listing 8-12: Program That Checks for Blank Fields

<?php
/* Program name: checkBlank.php
* Description: Program checks all the form fields for
* blank fields.
*/
?>
<html>
<head><title>Empty fields</title></head>
<body>
<?php
/* set up array of field labels */
$label_array = array ( “first_name” => “First Name”, “middle_name” => “Middle Name”, “last_name” => “Last Name”, “phone” => “Phone”);
/* check each field except middle name for blank fields */
foreach ($_POST as $field => $value)
{
if ($field != “middle_name”)
{
if ( $value == “” )
{
$blank_array[$field] = “blank”;
}
}
} // end of foreach loop for $_POST
/* if any fields were blank, display error message and form */
if (@sizeof($blank_array) > 0) //if blank fields are found
{
echo “<b>You didn’t fill in one or more required fields.
You must enter:</b><br>”;
/* display list of missing information */
foreach($blank_array as $field => $value)
{
echo “&nbsp;&nbsp;&nbsp;{$label_array[$field]}<br>”;
} //end of foreach loop for blanks
/* redisplay form */
$first_name=trim(strip_tags($_POST[‘first_name’]));
$middle_name=trim(strip_tags($_POST[‘middle_name’]));
$last_name=trim(strip_tags($_POST[‘last_name’]));
$phone=trim(strip_tags($_POST[‘phone’]));
echo “<p><hr>
<form action=’checkBlank.php’ method=’POST’>
<center>
<table width=’95%’ border=’0’ cellspacing=’0’
cellpadding=’2’>
<tr><td align=’right’><b>{$label_array[‘first_name’]}:
</br></td>
<td><input type=’text’ name=’first_name’ size=’65’
maxlength=’65’
value=’{$first_name}’ ></td>

Listing 8-11: Program to Build a List of Check Boxes

<?php
/* Program name: buildCheckbox.php
* Description: Program displays a list of
* checkboxes from database info.
*/
echo “<html>
<head><title>Pet Types</title></head>
<body>”;
$user=”catalog”;
$host=”localhost”;
$password=””;
$database = “PetCatalog”;

$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);
$db = mysql_select_db($database,$connection)
or die (“Couldn’t select database”);
$query = “SELECT DISTINCT petType FROM Pet
ORDER BY petType”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

echo “<div style=’margin-left: .5in’>
<p>&nbsp;
<p><b>Which type of pet are you interested in?</b>
<p>Choose as many types of pets as you want:\n”;

/* create form containing checkboxes */
echo “<form action=’processform.php’ method=’POST’>\n”;

while ($row = mysql_fetch_array($result))
{
extract($row);
echo “<input type=’checkbox’ name=’interest[$petType]’
value=’$petType’>$petType\n”;
echo “<br>\n”;
}
echo “<p><input type=’submit’ value=’Select Type of Pet’>
</form>\n”;
?>
</div></body></html>

This program is very similar to the program in Listing 8-10 that builds a list of radio buttons. However, notice that the input field uses an array $interest as the name for the field. This is because more than one check box can be selected. This program will create an element in the array with a key/value pair for each check box that’s selected. For instance, if the user selects both horse and dragon, the following array is created:

$interest[horse]=horse
$interest[dragon]=dragon

The program that processes the form has the selections available in the POST
array, as follows:

$_POST[‘interest’][‘horse’]
$_POST[‘interest’][‘dragon’]

Figure 8-12 shows the Web page produced by buildCheckbox.php.

</tr>
<tr><td align=’right’><b>{$label_array[‘middle_name’]}:
</br></td>
<td><input type=’text’ name=’middle_name’ size=’65’
maxlength=’65’ value=’$middle_name’ > </td>
</tr>
<tr><td align=’right’><b>{$label_array[‘last_name’]}:
</b></td>
<td> <input type=’text’ name=’last_name’ size=’65’
maxlength=’65’ value=’$last_name’> </td>
</tr>
<tr><td align=’right’><b>{$label_array[‘phone’]}:
</b></td>
<td> <input type=’text’ name=’phone’ size=’65’
maxlength=’65’ value=’$phone’> </td>
</tr>
</table>
<p><input type=’submit’
value=’Submit name and phone number’>
</form>
</center>”;
exit();
}
echo “Welcome”;
?>
</body></html>

To check for blanks, the program does the following:

1. Sets up an array of field labels. These labels are used as labels in the form and are also used to display the list of missing information.

2. Loops through all the variables passed from the form, checking for blanks. The variables are in the array $ _POST. Any blank fields that are found are added to an array of blank fields $blank_array.

3. Checks whether any blank fields were found. Checks the number of items in $blank_array.

4. If zero blank fields were found, jumps to welcome message.

5. If one or more blank fields were found:

i. Displays an error message. This message explains to the user that some required information is missing.

ii. Displays a list of missing information. Loops through
$blank_array and displays the label(s).

iii. Displays the form. Because the form includes variable names in the value attribute, the information that the user previously entered is retrieved from $_POST and displayed.

iv. Exits. Stops after the form displays. The user must click the submit button to continue.

You also need to protect yourself from malicious users — users who might want to damage your Web site or your database or steal information from you or your users. You don’t want users to enter HTML tags into a form field — something that might have unexpected results when sent to a browser. A par­ ticularly dangerous tag would be a script tag that allows a user to enter a program into a form field.

If you check each field for its expected format, you can catch typo s and pre­ vent most malicious content. However, checking information is a balancing act. You want to catch as much incorrect data as possible, but you don’t want to block any legitimate information. For instance, when you check a phone number, you might limit it to numbers. The problem with this check is that
it would screen out legitimate phone numbers in the form 555-5555 or (888)
555-5555. So you also need to allow hyphens (-), parentheses ( ), and spaces. You might limit the field to a length of 14 characters, including parentheses, spaces, and hyphens, but this screens out overseas numbers or numbers that include an extension. The bottom line: You need to think carefully about what information you want to accept or screen out for any field.

You can check field information by using regular expressions, which are pat­ terns. You compare the information in the field against the pattern to see whether it matches. If it doesn’t match, the information in the field is incorrect, and the user must type it over. (See Chapter 6 for more on regular expressions.)

In general, these are the statements that you use to check fields:

if ( !ereg(“pattern”,$variablename) )
{
echo error message; redisplay form; exit();
}
echo “Welcome”;

Notice that the condition in the if statement is negative. That is, the ! (excla­ mation mark) means “not”. So, the if statement actually says: If the variable does not match the pattern, execute the if block.

For example, suppose that you want to check an input field that contains the user’s last name. You can expect names to contain letters, not numbers, and possibly apostrophe and hyphen characters (as in O’Hara and Smith-Jones, respectively) and also spaces (as in Van Dyke). Also, it’s difficult to imagine a name longer than 50 characters. Thus, you can use the following statements to check a name.

if ( !ereg(“[A-Za-z’ -]{1,50}”,$last_name)
{
echo error message; redisplay form; exit();
}
echo “Welcome”;

If you want to list a hyphen (-) as part of a set of allowable characters sur­ rounded by square brackets ( [ ] ), you must list the hyphen at the beginning or at the end of the list. Otherwise, if you put it between two characters, the program will interpret it as the range between the two characters, such as A–Z.

In the preceding section, you find out how to check every form field to ensure that it isn’t blank. In addition to that, you will probably also want to check all the fields that have data to be sure the data is in an acceptable format. You can check the format by making a few simple changes to the program in Listing 8-12. Listing 8-13 shows the modified program, called checkAll.php.

Listing 8-13: Program That Checks All the Data in Form Fields

<?php
/* Program name: checkAll.php
* Description: Program checks all the form fields for
* blank fields and incorrect format.
*/
?>
<html>

<head><title>Emp.ty fields</title></head>
<body>
<?php
/* set up array of field labels */
$label_array = array ( “first_name” => “First Name”, “middle_name” => “Middle Name”, “last_name” => “Last Name”, “phone” => “Phone”);
foreach ($_POST as $field => $value)
{
/* check each field except middle name for blank fields */
if ( $value == “” )
{
if ($field != “middle_name”)
{
$blank_array[$field] = “blank”;
}
}
elseif ($field == “first_name” or $field == “middle_name”
or $field == “last_name” )
{
if (!ereg(“^[A-Za-z’ -]{1,50}$”,$_POST[$field]) )
{

$bad_format[$field] = “bad”;
}
}
elseif ($field == “phone”)
{
if(!ereg(“^[0-9)( -]{7,20}(([xX]|(ext)|(ex))?[ -]?[0-9]{1,7})?$”,$value))
{
$bad_format[$field] = “bad”;
}
}
}
/* if any fields were not okay, display error message and form */
if (@sizeof($blank_array) > 0 or @sizeof($bad_format) > 0)
{
if (@sizeof($blank_array) > 0)
{
/* display message for missing information */
echo “<b>You didn’t fill in one or more required fields. You must enter:</b><br>”;
/* display list of missing information */
foreach($blank_array as $field => $value)
{
echo “&nbsp;&nbsp;&nbsp;{$label_array[$field]}<br>”;
}
}
if (@sizeof($bad_format) > 0)
{
/* display message for bad information */
echo “<b>One or more fields have information that appears to be incorrect. Correct the format for:</b><br>”;
/* display list of bad information */
foreach($bad_format as $field => $value)
{
echo “&nbsp;&nbsp;&nbsp;{$label_array[$field]}<br>”;
}
}
/* redisplay form */
$first_name = $_POST[‘first_name’];
$middle_name = $_POST[‘middle_name’];
$last_name = $_POST[‘last_name’];
$phone = $_POST[‘phone’];
echo “<p><hr>
<form action=’checkAll.php’ method=’POST’>
<center>
<table width=’95%’ border=’0’ cellspacing=’0’ cellpadding=’2’>
<tr><td align=’right’><B>{$label_array[‘first_name’]}:</br></td>
<td><input type=’text’ name=’first_name’ size=’65’ maxlength=’65’
value=’$first_name’ > </td>
</tr>
<tr><td align=’right’><B>{$label_array[‘middle_name’]}:</br></td>
<td><input type=’text’ name=’middle_name’ size=’65’ maxlength=’65’
value=’$middle_name’ > </td>

Remember, programs that process forms use the information from the form. If you run them by themselves, they don’t have any information passed from the form and will not run correctly. These programs are intended to run when the user presses the submit button for a form.

Don’t forget the exit statement. Without the exit statement, the program would continue and would display the welcome message after displaying the form.

Figure 8-13 shows the Web page that results if the user didn’t enter his or her first or middle name. Notice that the list of missing information doesn’t include Middle Name because Middle Name is not required. Also, notice that the information the user originally typed into the form is still displayed in the form fields.

Checking the format of the information
Whenever users must type information in a form, you can expect a certain number of typos. You can detect some of these errors when the form is submit­ ted, point out the error(s) to the user, and then request that he or she retype the information. For instance, if the user types 8899776 in the ZIP code field, you know this is not correct. This information is too long to be a ZIP code and too short to be a ZIP+4 code.

</tr>
<tr><td align=’right’><B>{$label_array[‘last_name’]}:</B></td>
<td> <input type=’text’ name=’last_name’ size=’65’ maxlength=’65’
value=’$last_name’> </td>
</tr>
<tr><td align=’right’><B>{$label_array[‘phone’]}:</B></td>
<td> <input type=’text’ name=’phone’ size=’65’ maxlength=’65’
value=’$phone’> </td>
</tr>
</table>
<p><input type=’submit’ value=’Submit name and phone number’>
</form>
</center>”;
exit();
}
echo “Welcome”;
?>
</body></html>

Here are the differences between this program and the program in Listing 8-12:

This program creates two arrays for problem data. It creates
$blank_array, as did the previous program. But this program also creates $bad_format for fields that contain information that is not in an acceptable format.

This program loops through $bad_format to create a separate list of problem data. If any fields are blank, it creates one error message and list of problem fields, as did the previous program. If any fields are in an unacceptable format, this program also creates a second error message and list of problem fields.

The Web page in Figure 8-14 results when the user accidentally types his or her first name into the Middle Name field and also types nonsense for his or her phone number. Notice that two error messages appear, showing that
the First Name field is blank and that the Phone field contains incorrect information.

Giving users a choice with multiple submit buttons

You can use more than one submit button in a form. For instance, in a cus­ tomer order form, you might use a button that reads Submit Order and another button that reads Cancel Order. However, you can only list one program in the action=programname part of your form tag, meaning that the two buttons
run the same program. PHP solves this problem. By using PHP, you can process the form differently, depending on which button the user clicks.
The following statements create a form with two submit buttons:

<form action=”twoButtons.php” method=”POST”>
<input type=”text” name=”last_name” maxlength=”50”><br>
<input type=”submit” name=”display_button”
value=”Show Address”>
<input type=”submit” name=”display_button”
value=”Show Phone Number”>
</form>

Notice that the submit button fields have a name: display_button. The fields each have a different value. Whichever button the user clicks sets the value for $display_button. The program twoButtons.php in Listing 8-14 processes the preceding form.

Listing 8-14: Program That Processes Two Submit Buttons

<?php
/* Program name: twoButtons.php
* Description: Program displays different information
* depending on which submit button was
* pushed.

(continued)

Listing 8-14 (continued)

*/
?>
<html>
<head><title>Member Address or Phone Number</title></head>
<body>
<?php
$user=”admin”;
$host=”localhost”;
$password=””;
$database = “MemberDirectory”;
$connection = mysql_connect($host,$user,$password)
or die (“couldn’t connect to server”);
$db = mysql_select_db($database,$connection)
or die (“Couldn’t select database”);
if ($_POST[‘display_button’] == “Show Address”)
{
$query = “SELECT street,city,state,zip FROM Member
WHERE lastName=’$_POST[last_name]’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);
$row = mysql_fetch_array($result);
extract($row);
echo “$street<br>$city, $state $zip<br>”;
}
else
{
$query = “SELECT phone FROM Member
WHERE lastName=’$_POST[last_name]’”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);
$row = mysql_fetch_array($result);
echo “Phone: {$row[‘phone’]}<br>”;
}
?>
</body></html>

The program executes different statements, depending on which button is clicked. If the user clicks the button for the address, the program outputs the address for the name submitted in the form; if the user clicks the Show Phone Number button, the program outputs the phone number.

Putting Information into a Database

Your application probably needs to store data in your database. For example, your database might store information that a user typed into a form for your use — a Member Directory is a good example of this. Or your database might store data temporarily during the application. Either way, you store data by sending SQL queries to MySQL. (I explain SQL queries in detail in Chapter 4.)

Preparing the data

You need to prepare the data before storing it in the database. Preparing the data includes the following:

Putting the data into variables

Making sure that the data is in the format expected by the database

Cleaning the data

Putting the data into variables
You store the data by sending it to the database in an SQL query. You store the data in variables and include the variable names in the query. By using PHP, this process is simple. The user provides most of the data that you want to store via a form. As I discuss earlier in this chapter, PHP stores the data in a variable with the name of the form field, invisibly and automatically, with­ out your having to store it yourself. You just use the variables that PHP pro­
vides. Occasionally, you want to store information that you generate yourself, such as today’s date or a customer order number. You just need to store this information in a variable so that you can include it in a query.

Using the correct format
When you design your database, you set the data type for each column. The data that you want to store must match the data type of the column that you want to store it in. For instance, if the column expects a data type integer, the data sent must be numbers. Or if the column expects data that’s a date, the data that you send must be in a format that MySQL recognizes as a date. If you send incorrectly formatted data, MySQL still stores the data, but it might not store the value that you expected. Here’s a rundown of how MySQL stores
data for the most frequently used data types:

CHAR or VARCHAR: Stores strings. MySQL stores pretty much any data sent to a character column, including numbers or dates, as strings. When you created the column, you specified a length. For example, if you specified CHAR(20), only 20 characters can be stored. If you send a string longer than 20 characters, only the first 20 characters are stored. The remaining characters are dropped.

Set the maxlength for any text input fields in a form to the same length as the column width in the database where the data will be stored. That way, the user can’t enter any more characters than the database can store.

INT or DECIMAL: Stores numbers. MySQL will try to interpret any data sent to a number column as a number, whether it makes sense or not. For instance, it might interpret a date as a number, and you could end up with a number like 2001.00. If MySQL is completely unable to interpret the data sent as a number, it stores 0 (zero) in the column.

DATE: Stores dates. MySQL expects dates as numbers, with the year first, month second, and day last. The year can be two or four digits (2001 or
01). The date can be a string of numbers, or each part can be separated by a hyphen (-), a period (.), or a forward slash ( / ). Some valid date for­ mats are 20011203, 980103, 2001-3-2, and 2000.10.01. If MySQL cannot interpret the data sent as a date, it stores the date as 0000-00-00.

ENUM: Stores only the values that you allowed when you created the
column. If you send data that is not allowed, MySQL stores a 0.

In many cases, the data is collected in a form and stored in the database as-is. For instance, users type their names in a form, and the program stores them. However, in some cases, the data needs to be changed before you store it. For instance, if a user enters a date into a form in three separate selection lists for month, day, and year (as I describe in the section, “Building selection lists,” earlier in this chapter), the values in the three fields must be put together into one variable. The following statements put the fields together:

$expDate = $_POST[‘expYear’].”-”;
$expDate .= $_POST[‘expMonth’].”-”;
$expDate .= $_POST[‘expDay’];

Another case in which you might want to change the data before storing it is when you’re storing phone numbers. Users enter phone numbers in a variety of formats, using parentheses, dashes, dots, or spaces. Rather than storing these varied formats in your database, you might just store the numbers. Then when you retrieve a phone number from the database, you can format the number however you want before you display it. The following statement removes characters from the string:

$phone = ereg_replace(“[ )(.-]”,””,$_POST[‘phone’]);

The function ereg_replace uses regular expressions to search for a pattern. The first string passed is the regular expression to match. If any part of the string matches the pattern, it is replaced by the second string. In this case, the regular expression is [ )(.-], which means any one of the characters in the square brackets. The second string is “”, which is a string with nothing in it. Therefore, any spaces, parentheses, dots, or hyphens in the string are replaced by nothing.

Cleaning the data
The earlier section “Getting Information from the User,” which describes the use of HTML forms, discusses checking the data in forms. Users can type data into a text field, either accidentally or maliciously, that can cause prob­ lems for your application, your database, or your users. Checking the data and accepting only the characters expected for the information requested
can prevent many problems. However, you can miss something. Also, in some

cases, the information that the user enters needs to allow pretty much any­ thing. For instance, you normally wouldn’t allow the characters < and > in a field. However, there might be a situation in which the user needs to enter these characters — perhaps the user needs to enter a technical formula or specification that requires them.

PHP provides two functions that can clean the data, thus rendering it harmless:

strip_tags: This function removes all text enclosed by < and > from the data. It looks for an opening < and removes it and everything else, until it finds a closing > or reaches the end of the string. You can include specific tags that you want to allow. For instance, the following state­ ment removes all tags from a character string except <b> and <i>:

$last_name = strip_tags($last_name,”<b><i>”);

htmlspecialchars: This function changes some special characters with meaning to HTML into an HTML format that allows them to be dis­ played without any special meaning. The changes are

• < becomes &lt;

• > becomes &gt;

• & becomes &amp;

In this way, the characters < and > can be displayed on a Web page with­ out being interpreted by HTML as tags. The following statement changes these special characters:

$last_name = htmlspecialchars($last_name);

If you’re positive that you don’t want to allow your users to type any < or > characters into a form field, use strip_tags. However, if you want to allow < or > characters, you can safely store them after they have been processed by htmlspecialchars.

Another function that you should use before storing data in your database is trim. Users often type spaces at the beginning or end of a text field without meaning to. Trim removes any leading or trailing spaces so they don’t get stored. Use the following statement to remove these spaces:

$last_name = trim($_POST[‘last_name’]);

Adding new information

You use the INSERT query (described in Chapter 4) to add new information to the database. INSERT adds a new row to a database table. The general format is

$query = “INSERT INTO tablename (col,col,col...) VALUES (‘var’,’var’,’var’...)”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

For instance, the statements to store the name and phone number that a user entered in a form are

$firstName = “Goliath”; // from form field
$lastName = “Smith”; // from form field
$phone = “555-555-5555”; // from form field
$query = “INSERT INTO Member (lastName,firstName,phone)
VALUES (‘$lastName’,’$firstName’,’$phone’)”;
$result = mysql_query($query)
or die (“Couldn’t execute query.”);

Listing 8-15 shows a program called savePhone.php that stores a name and a phone number from a form.

Listing 8-15: Program That Stores Data from a Form

<?php
/* Program name: savePhone.php
* Description: Program checks all the form fields for
* blank fields and incorrect format. Saves the
* correct fields in a database.
*/
?>
<html>
<head><title>Member Phone Number</title></head>
<body>
<?php
$first_name = strip_tags(trim($_POST[‘first_name’]));
$last_name = strip_tags(trim($_POST[‘last_name’]));
$phone = strip_tags(trim($_POST[‘phone’]));
$phone = ereg_replace(“[)( .-]”,””,$phone);

/* check information from the form */

/* set up array of field labels */
$label_array = array ( “first_name” => “First Name”, “last_name” => “Last Name”, “phone” => “Phone”);
foreach ($_POST as $field => $value)
{
/* check each field for blank fields */
if ( $value == “” )
{
$blank_array[$field] = “blank”;
}
elseif ( ereg(“(name)”,$field) )

0 comments: