PHP Chapter 9
PHP Chapter 9
9
MANIPULATING MYSQL
DATABASES WITH PHP
In this chapter, you will:
♦ Connect to MySQL from PHP
♦ Learn how to handle MySQL errors
♦ Execute SQL statements with PHP
♦ Use PHP to work with MySQL databases and tables
♦ Use PHP to manipulate database records
419
420 Chapter 9 Manipulating MySQL Databases with PHP
MySQL, mainly because they are free and fairly easy to learn. After you select a data-
base, you need to determine whether PHP can access it directly or whether it must go
through a layer such as ODBC or PEAR DB. Going through ODBC or PEAR DB
makes it easier for you to write PHP code that can be used with a variety of databases.
However, your PHP script will be faster if it can access a database directly, without going
through a PEAR DB or ODBC layer.Therefore, if you anticipate that your PHP script
will need to access more than one type of database, you should use PEAR DB or
ODBC. To be more precise, you should use PEAR DB over ODBC because PEAR is
designed specifically for the PHP language.Yet, there are cases when ODBC is prefer-
able, especially when you need to access Microsoft data source products such as
Microsoft Access or Microsoft Excel. However, if you plan to work with a single data-
base, such as MySQL, and you are more concerned with your Web application’s perfor-
mance than whether it is compatible with multiple database systems, use PHP’s direct
database access functionality if it’s available for your database management system.
In this chapter, you study how to use PHP to directly access MySQL.
The mysqli extension is designed to work with MySQL version 4.1.3 and
higher. If you are using a version of MySQL that is older that 4.1.3, you must
use the mysql extension.
How you enable MySQL support in PHP depends on your operating system and how
you installed PHP. On UNIX/Linux systems, you configure PHP to use the mysqli
extension by specifying the --with-mysqli parameter when you run the configure
Connecting to MySQL with PHP 421
command during the PHP installation process. If you followed the UNIX/Linux PHP
installation instructions in Chapter 2, you should have specified the --with-mysqli
parameter when you ran the configure command. If you did not specify the --with-
mysqli parameter when you ran the configure command, you need to reinstall PHP
to complete the exercises in this chapter.
To enable the mysqli extension on Windows installations of PHP, you must copy two
files, libmysql.dll and php_mysqli.dll, to the directory where you installed PHP.You must
also edit your php.ini configuration file and enable the extension=php_mysqli.dll
directive.The libmysql.dll and php_mysqli.dll files are available in the full PHP Windows
zip package (not the Windows binary installer) that is available on the PHP download
page. The following instructions describe how to enable MySQL support on Windows
installations of PHP.
If you are working with an installation of PHP that is hosted by an ISP, MySQL
support should already be enabled.
The following steps assume that you followed the instructions in Chapter 2
9
to install PHP with the Windows binary installer. If you installed PHP by using
the full PHP Windows zip package, the libmysql.dll file is installed by default
in the PHP installation directory and the php_mysqli.dll file is installed in the
ext directory beneath the PHP installation directory. You only need to copy
the php_mysqli.dll file from the ext directory to the main PHP installation
directory and enable the extension=php_mysqli.dll directive, as
described in the following steps.
5. Open your php.ini configuration file in your text editor. On Windows sys-
tems, this file is installed automatically in your main Windows directory,
which is usually C:\WINDOWS or C:\WINNT.
6. In the php.ini file, locate the extension=php_mysqli.dll directive (not
the extension=php_mysql.dll directive) and remove the semicolon at
the beginning of the line to enable MySQL support. If the
extension=php_mysqli.dll directive does not exist in your php.ini file,
add it to the end of the Windows Extensions section.
7. Save and close the php.ini file.
8. Restart your Web server.
In the preceding, the host argument allows you to specify the host name where your
MySQL database server is installed. If you are working with an instance of MySQL data-
base server that is installed on your local computer, use a value of “localhost” or
“127.0.0.1” for the host argument. However, if you are working with a MySQL database
server on an ISP’s Web site, you need to enter your ISP’s host name.The user and password
arguments allow you to specify a MySQL account name and password, and the database
argument allows you to select a database with which to work. For example, the follow-
ing command connects the username dongosselin with a password of “rosebud” to a local
instance of MySQL database server and opens a database named real_estate. The
database connection is assigned to the $DBConnect variable.
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"dongosselin",ƒ
ƒƒƒƒƒ"rosebud",ƒ"real_estate");
Connecting to MySQL with PHP 423
When your PHP script ends, any open database connections close automatically.
However, you should get into the habit of explicitly closing database connections with
the mysqli_close() function when you are finished with them to ensure that the
connection doesn’t keep taking up space in your computer’s memory while the script
finishes processing.You close a database connection by passing the database connection
variable to the mysqli_close() function. The following statement closes the
$DBConnect database connection variable that was opened in the preceding statement:
mysqli_close($DBConnect);
If you receive a warning that PHP is unable to load a dynamic library or an error
such as “Call to undefined function mysqli_connect(),” MySQL support is
not correctly enabled for your PHP installation. For more information, refer to
the “Enabling MySQL Support in PHP” section earlier in this chapter. 9
After you connect to a database with the mysqli_connect() function, you can use the
functions listed in Table 9-1 to return information about your installation of MySQL server.
Next, you create a PHP script that connects to MySQL and uses the functions listed in
Table 9-1 to print information about your installation of MySQL.
424 Chapter 9 Manipulating MySQL Databases with PHP
To create a PHP script that connects to MySQL and uses the functions listed in Table 9-1
to print information about your installation of MySQL:
1. Create a new document in your text editor.
2. Type the <!DOCTYPE> declaration, <html> element, header information,
and <body> element. Use the strict DTD and “MySQL Server Information”
as the content of the <title> element.
3. Add the following <link> element above the closing </head> tag to link
to the php_styles.css style sheet in your Chapter directory:
<linkƒrel="stylesheet"ƒhref="php_styles.css"ƒtype="text/css"ƒ/>
Next, you create a PHP script that selects the flightlog database you created in
Chapter 8.
To create a PHP script that selects the flightlog database you created in Chapter 8:
1. Create a new document in your text editor.
2. Type the <!DOCTYPE> declaration, <html> element, header information,
and <body> element. Use the strict DTD and “Flightlog Entries” as the con-
tent of the <title> element.
426 Chapter 9 Manipulating MySQL Databases with PHP
3. Add the following <link> element above the closing </head> tag to link
to the php_styles.css style sheet in your Chapter directory:
<linkƒrel="stylesheet"ƒhref="php_styles.css"ƒtype="text/css"ƒ/>
The problem with the preceding code is that, although it prints “The database server is
not available” if you cannot connect to the database server, it also prints any error mes-
sages that may be caused by the mysqli_connect() function. For example, Figure 9-2
displays an error message that occurs if you attempt to access the database with an invalid 9
username or password.
As with the connection to the database server, you should also check to ensure that the
mysqli_select_db() function successfully selects the database. Because the
mysqli_select_db() function returns a value of true if it is successful, you can call the
function from within an if statement’s conditional expression. The following code
demonstrates how to call the mysqli_select_db() function from within an if state-
ment’s conditional expression to determine whether the database was selected successfully:
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"dongosselin",ƒ"rosebud");
ifƒ(!$DBConnect)
ƒƒƒƒƒƒechoƒ"<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</p>";
elseƒƒƒ{
428 Chapter 9 Manipulating MySQL Databases with PHP
ƒƒƒƒƒechoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
ƒƒƒƒƒƒifƒ(mysqli_select_db($DBConnect,ƒ"flightlog"))ƒ{
ƒƒƒƒƒƒƒƒƒƒƒƒechoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</p>";
ƒƒƒƒƒƒƒƒƒƒƒƒ//ƒadditionalƒstatementsƒthatƒaccessƒtheƒdatabase
ƒƒƒƒƒƒ}
ƒƒƒƒƒƒelse
ƒƒƒƒƒƒƒƒƒƒƒƒechoƒ"<p>Theƒdatabaseƒisƒnotƒavailable.</p>";
ƒƒƒƒƒƒmysqli_close($DBConnect);
}
In most cases, the mysqli_select_db() function does not print any error messages
the way the mysqli_connect() function does. However, to be on the safe side, you
should suppress any error codes that may appear for both the mysqli_connect()
function and the mysqli_select_db() function. In the next section, you learn how
to suppress errors with the error control operator.
Next, you modify the FlightlogEntries.php script so it verifies that the database is con-
nected and that the flightlog database is selected.
To modify the FlightlogEntries.php script so it verifies that the database is connected
and that the flightlog database is selected:
1. Return to the FlightlogEntries.php document in your text editor.
2. Modify the script section so it verifies that the database is connected and that
the flightlog database is selected, as follows:
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"user",ƒ"password");
ifƒ(!$DBConnect)
ƒƒƒƒƒechoƒ"<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</p>";
elseƒƒ{
echoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
ƒƒƒƒƒ$DBNameƒ=ƒ"flightlog";
ƒƒƒƒƒifƒ(mysqli_select_db($DBConnect,ƒ$DBName))
ƒƒƒƒƒƒƒƒƒƒechoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</p>";
ƒƒƒƒƒelse
ƒƒƒƒƒƒƒƒƒƒechoƒ"<p>Theƒdatabaseƒisƒnotƒavailable.</p>";
ƒƒƒƒƒmysqli_close($DBConnect);
}
3. Save the FlightlogEntries.php file and open it in your Web browser by
entering the following URL: http://localhost/PHP_Projects/
Chapter.09/Chapter/FlightlogEntries.php.Your Web browser should
appear similar to Figure 9-3.
Handling MySQL Errors 429
Another method of bulletproofing your code is to use the error control operator (@) to sup-
press error messages.You can place the error control operator before any expression, although
it is most commonly used with built-in PHP functions, especially functions that access data
430 Chapter 9 Manipulating MySQL Databases with PHP
Next, you add error control operators to the mysqli_connect() and mysqli_
select_db() functions in the FlightlogEntries.php script.
To add error control operators to the mysqli_connect() and mysqli_select_
db() functions in the FlightlogEntries.php script:
1. Return to the FlightlogEntries.php document in your text editor.
2. Add error control operators before the mysqli_connect() and
mysqli_select_db() functions.
3. Save the FlightlogEntries.php file and open it in your Web browser by
entering the following URL:
http://localhost/PHP_Projects/Chapter.09/Chapter/FlightlogEntries
.php. The Web page should appear the same as it did before you added the
error control operators.
4. Close your Web browser window.
You can find a list of error codes that may be returned from the
mysqli_sqlstate() function at http://dev.mysql.com/doc/mysql/en/
error-handling.html.
As an example of how you might use a MySQL error reporting function, consider a
PHP script that allows users to submit a username and password that will be used to log
on to MySQL. For example, a Web page may contain the following simple form that
will be submitted to a PHP script named dblogin.php:
<formƒaction="dblogin.php"ƒmethod="GET"ƒ
enctype="application/x-www-form-urlencoded">
<p>Usernameƒ<inputƒtype="text"ƒname="username"ƒ/><brƒ/>
Passwordƒ<inputƒtype="password"ƒname="password"ƒ/></p>
<p><inputƒtype="submit"ƒvalue="LogƒIn"ƒ/></p>
</form>
If a user enters an invalid username or password with the preceding form, printing a
generic message such as “The database server is not available” doesn’t help him deter-
mine what’s wrong.When connecting to the MySQL database server, you should at least
use the mysqli_connect_error() function to give the user more information about 9
the error that occurred. For example, the die() function in the following code uses the
mysqli_connect_errno() and the mysqli_connect_error() functions to print
an error code and message if the connection attempt fails. Both of these functions report
on the most recent database connection attempt. If the user enters an invalid username
or password in the form, he will see the error number and description shown in Figure
9-4. As you can see in the figure, the error description informs users that access was
denied for the submitted username and password, which should point out that either a
typo occurred in the submitted username or password, or that the user doesn’t have
authorization to access the database.
$Userƒ=ƒ$_GET['username'];
$Passwordƒ=ƒ$_GET['password'];
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ$User,ƒ$Password)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒconnectƒtoƒtheƒdatabaseƒserver.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_connect_errno()
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_connect_error())ƒ.ƒ"</p>";ƒ
echoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
@mysqli_select_db($DBConnect,ƒ"flightlog")
ƒƒƒƒƒOrƒdie("<p>Theƒdatabaseƒisƒnotƒavailable.</p>");
echoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</p>";
//ƒadditionalƒstatementsƒthatƒaccessƒtheƒdatabase
mysqli_close($DBConnect);
434 Chapter 9 Manipulating MySQL Databases with PHP
Figure 9-4 Error number and message generated by an invalid username and password
Figure 9-5 Error code and message generated when attempting to select a database that
does not exist
Next, you modify the die() functions in the FlightlogEntries.php script so they print
error codes and messages in the event of an error.
To modify the die() functions in the FlightlogEntries.php script so they print error
codes and messages in the event of an error:
1. Return to the FlightlogEntries.php document in your text editor. 9
2. Modify the die() function in the mysqli_connect() statement so it
includes the mysqli_connect_errno() and
mysqli_connect_error() functions, as follows:
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ
"dongosselin","rosebud")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒconnectƒtoƒtheƒdatabaseƒserver.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_connect_errno()
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_connect_error())ƒ.ƒ"</p>";
3. Modify the die() function in the mysqli_select_db() statement so it
includes the mysqli_errno() and mysqli_error() functions, as follows:
@mysqli_select_db($DBConnect,ƒ$DBName)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒselectƒtheƒdatabase.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
4. Save the FlightlogEntries.php file and open it in your Web browser by
entering the following URL: http://localhost/PHP_Projects/
Chapter.09/Chapter/FlightlogEntries.php. The Web page should appear
the same as it did before you added the error functions.
5. Close your Web browser window.
436 Chapter 9 Manipulating MySQL Databases with PHP
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<p>Successfullyƒexecutedƒtheƒquery.</p>";
mysqli_close($DBConnect);
When you use a PHP variable to represent a field name in a SQL query, you must
enclose the variable name within single quotes or you receive an error. For example, the
following statement raises an error because the $Make variable is not enclosed within
single quotes:
$Makeƒ=ƒ"Ovation";
$SQLstringƒ=ƒ"SELECTƒmodel,ƒquantityƒFROMƒ$DBTableƒ
ƒƒƒƒƒWHEREƒmodel=$Make";
To fix the preceding code, enclose the $Make variable in single quotes, as follows:
$Makeƒ=ƒ"Ovation";
$SQLstringƒ=ƒ"SELECTƒmodel,ƒquantityƒFROMƒ$DBTableƒ
ƒƒƒƒƒWHEREƒmodel='$Make'";
Next, you add query statements to the FlightlogEntries.php script that select all the 9
records in the flightsessions table.
To query statements to the FlightlogEntries.php script that select all the records in the
flightsessions table:
1. Return to the FlightlogEntries.php document in your text editor.
2. Add the following statements above the mysqli_close() statement.
The first statement creates a SQL query that selects all records from the
flightsessions table. The second statement executes the query with the
mysqli_query() function, and the third statement prints a message if the
query is successful.
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒflightsessions";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<p>Successfullyƒexecutedƒtheƒquery.</p>";
3. Save the FlightlogEntries.php file and open it in your Web browser by
entering the following URL: http://localhost/PHP_Projects/
Chapter.09/Chapter/FlightlogEntries.php.You should see the three suc-
cess messages printed to the Web browser window.
4. Close your Web browser window.
438 Chapter 9 Manipulating MySQL Databases with PHP
First, you learn how to use the mysqli_fetch_row() function to retrieve fields into
an indexed array.
echoƒ"<p><strong>Make</strong>:ƒ{$Row[0]}<brƒ/>";
echoƒ"<strong>Model</strong>:ƒ{$Row[1]}<brƒ/>";
echoƒ"<strong>Price</strong>:ƒ{$Row[2]}<brƒ/>";
echoƒ"<strong>Quantity</strong>:ƒ{$Row[3]}</p>";
The mysqli_fetch_row() function returns the fields in the current row or a value
of false when it reaches the last row in the resultset. This allows you to iterate through
all the rows in a resultset.The following code shows a more complex example that uses
a do...while statement to print all of the rows in the inventory table to an HTML
table. Figure 9-6 shows how the table appears in a Web browser.
echoƒ"<tableƒwidth='100%'ƒborder='1'>";
echoƒ"<tr><th>Make</th><th>Model</th>
ƒƒƒƒƒ<th>Price</th><th>Quantity</th></tr>";
$Rowƒ=ƒmysqli_fetch_row($QueryResult);
doƒ{
ƒƒƒƒƒechoƒ"<tr><td>{$Row[0]}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row[1]}</td>";
ƒƒƒƒƒechoƒ"<tdƒalign='right'>{$Row[2]}</td>";
ƒƒƒƒƒechoƒ"<tdƒalign='right'>{$Row[3]}</td></tr>";
ƒƒƒƒƒ$Rowƒ=ƒmysqli_fetch_row($QueryResult);
9
}ƒwhileƒ($Row);
Next, you add query statements to the FlightlogEntries.php script that select all the
records in the flightsessions table.
440 Chapter 9 Manipulating MySQL Databases with PHP
To add query statements to the FlightlogEntries.php script that select all the records in
the flightsessions table:
1. Return to the FlightlogEntries.php document in your text editor.
2. Delete the following echo() statement that prints when the script success-
fully connects to the database server:
echoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
3. Delete the following echo() statement that prints when the database opens
successfully:
echoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</p>";
4. Replace the statement that prints when the query executes successfully with
the following statements, which use the mysqli_fetch_row() function to
print the results in a table:
echoƒ"<tableƒwidth='100%'ƒborder='1'>";
echoƒ"<tr><th>FlightƒDate</th><th>FlightƒTime</th>
<th>Origin</th><th>Destination</th><th>Weather</th><th>Winds</th>
<th>Temp</th></tr>";
$Rowƒ=ƒmysqli_fetch_row($QueryResult);
doƒ{
ƒƒƒƒƒechoƒ"<tr><td>{$Row[0]}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row[1]}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row[2]}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row[3]}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row[4]}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row[5]}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row[6]}</td></tr>";
ƒƒƒƒƒ$Rowƒ=ƒmysqli_fetch_row($QueryResult);
}ƒwhileƒ($Row);
The following code shows an associative array version of the do...while statement
that prints all of the rows in the inventory table to an HTML table:
echoƒ"<tableƒwidth='100%'ƒborder='1'>";
echoƒ"<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Quantity</th></tr>";
doƒ{
ƒƒƒƒƒ$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
ƒƒƒƒƒechoƒ"<tr><td>{$Row['make']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['model']}</td>";
ƒƒƒƒƒechoƒ"<tdƒalign='right'>{$Row['price']}</td>";
ƒƒƒƒƒechoƒ"<tdƒalign='right'>{$Row['quantity']}</td></tr>";
}ƒwhileƒ($Row);
Next, you add query statements to the FlightlogEntries.php script that select all the
records in the flightsessions table.
To query statements to the FlightlogEntries.php script that select all the records in the
flightsessions table:
1. Return to the FlightlogEntries.php document in your text editor.
2. Replace the two mysqli_fetch_row() functions with
mysqli_fetch_assoc() functions.
3. Modify the echo() statements in the do...while statement so they refer-
ence the keys in the associative array instead of the index values.Your modi-
fied code should appear as follows:
echoƒ"<tableƒwidth='100%'ƒborder='1'>";
echoƒ"<tr><th>FlightƒDate</th><th>FlightƒTime</th>
<th>Origin</th><th>Destination</th><th>Weather</th><th>Winds</th>
<th>Temp</th></tr>";
$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
doƒ{
ƒƒƒƒƒechoƒ"<tr><td>{$Row['flight_date']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['flight_time']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['origin']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['destination']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['weather']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['winds']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['temp']}</td></tr>";
ƒƒƒƒƒ$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
}ƒwhileƒ($Row);
Figure 9-8 Output of the number of rows and fields returned from a query
444 Chapter 9 Manipulating MySQL Databases with PHP
Next, you add statements to the FlightlogEntries.php script that print the number of
returned rows and fields.
To add statements to the FlightlogEntries.php script that print the number of returned
rows and fields:
1. Return to the FlightlogEntries.php document in your text editor.
2. Add the following statements above the above the
mysqli_close($DBConnect); statement:
$NumRowsƒ=ƒmysqli_num_rows($QueryResult);
$NumFieldsƒ=ƒmysqli_num_fields($QueryResult);
echoƒ"<p>Yourƒqueryƒreturnedƒtheƒfollowingƒ"ƒ
ƒƒƒƒƒ.ƒmysqli_num_rows($QueryResult)ƒ
ƒƒƒƒƒ.ƒ"ƒrowsƒandƒ".ƒmysqli_num_fields($QueryResult)ƒ
ƒƒƒƒƒ.ƒ"ƒfields:</p>";
3. Save the FlightlogEntries.php file and open it in your Web browser by
entering the following URL: http://localhost/PHP_Projects/
Chapter.09/Chapter/FlightlogEntries.php.Your Web page should appear
the same as it did before you added modified the code to use
mysqli_fetch_assoc() functions.
4. Close your Web browser window.
You can only use the mysqli_free_result() function with SQL state-
ments that return results, such as SELECT queries. If you attempt to use the
mysqli_free_result() function with SQL statements that do not return
results, such as the CREATE DATABASE and CREATE TABLE statements,
you receive an error.
For information that you want to store permanently, you should use the MySQL
Monitor instead of PHP to create and delete databases and tables. Creating and
deleting databases and tables with PHP is most useful when you only need to
temporarily store information for the current Web browser session.
If the mysqli_query() function successfully creates the database, you see the
“Successfully executed the query” message shown in the preceding example. If the data-
base already exists, you see the error code and message shown in Figure 9-9.
Figure 9-9 Error code and message that prints when you attempt to create a database
that already exists
To avoid the error message shown in Figure 9-9, you should use the mysqli_
db_select() function to check whether a database exists before you create or delete
it. The following code attempts to select the real_estate database with the
mysqli_db_select() function. Notice that the mysqli_db_select() function is
preceded by the error control operator to suppress errors. If the mysqli_db_select()
function successfully selects the real_estate database, the message “The real_estate
database already exists!” prints to the Web browser. Otherwise, the statements in the
else clause create the database.
$DBNameƒ=ƒ"real_estate";
ifƒ(@mysqli_select_db($DBConnect,ƒ$DBName))
ƒƒƒƒƒechoƒ"<p>Theƒ$DBNameƒdatabaseƒalreadyƒexists!</p>";
elseƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒDATABASEƒ$DBName";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Successfullyƒcreatedƒtheƒdatabase.</p>";
mysqli_select_db($DBConnect,ƒ$DBName)
}
mysqli_close($DBConnect);
Working with Databases and Tables 447
As with the MySQL Monitor, creating a new database does not select it. To use a new
database, you must select it by executing the mysqli_select_db() function. The
real_estate database is selected at the end of the else clause in the preceding code.
Deleting a database is almost identical to creating one, except that you use the DROP
DATABASE statement instead of the CREATE DATABASE statement with the
mysqli_query() function. The following code demonstrates how to delete the
real_estate database. Notice that the code uses the same error-handling functional-
ity as the code that created the database.
$DBNameƒ=ƒ"real_estate";
...
ifƒ(@!mysqli_select_db($DBConnect,ƒ$DBName))
ƒƒƒƒƒechoƒ"<p>Theƒ$DBNameƒdatabaseƒdoesƒnotƒexist!</p>";
elseƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"DROPƒDATABASEƒ$DBName";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Successfullyƒdeletedƒtheƒdatabase.</p>";
9
}
mysqli_close($DBConnect);
In the rest of this chapter, you work on a Web site for registering students in scuba div-
ing classes for a company named Aqua Don’s Scuba School. Student information and class
registrations will be stored in a MySQL database named scuba_school consisting of
two tables: divers and registration. The divers table contains each diver’s ID,
along with other personal information. The registration table contains a record for
each class in which a diver enrolls. The divers table is the primary table, and the
diverID field acts as the primary key.The diverID field also acts as the foreign key in
the registration table. Because each student can enroll in more than one class, the
relationship between the students table and the registration table is one-to-many;
the students table is the one side of the relationship, and the registration table is
the many side of the relationship.Your Chapter directory for Chapter 9 contains a doc-
ument named Registration.html that you will use to call some PHP scripts that access
the MySQL database. Figure 9-10 shows the Registration.html page in a Web browser.
448 Chapter 9 Manipulating MySQL Databases with PHP
First, you create a script named GetDiverID.php that registers divers with Aqua Don’s
Scuba School. You add code to the GetDiverID.php script that creates the
scuba_school database the first time the script is called.
To create the GetDiverID.php script:
1. Create a new document in your text editor.
2. Type the <!DOCTYPE> declaration, <html> element, header information,
and <body> element. Use the strict DTD and “Register Diver” as the con-
tent of the <title> element.
3. Add the following <link> element above the closing </head> tag to link
to the php_styles.css style sheet in your Chapter directory:
<linkƒrel="stylesheet"ƒhref="php_styles.css"ƒtype="text/css"ƒ/>
4. Add the following heading element to the document body:
<h1>AquaƒDon'sƒScubaƒSchoolƒRegistration</h1>
5. Add the following script section to the end of the document body:
<?php
?>
Working with Databases and Tables 449
6. Add the following statements to the script section to ensure that users enter
all the fields in New Diver Registration form:
ifƒ(empty($_GET['first_name'])ƒ||ƒempty($_GET['last_name'])ƒ||ƒ
empty($_GET['phone'])ƒ||ƒempty($_GET['address'])ƒ||ƒ
empty($_GET['city'])ƒ||ƒempty($_GET['state'])ƒ||ƒ
empty($_GET['zip'])ƒ||ƒempty($_GET['email']))
ƒƒƒƒƒexit("<p>YouƒmustƒenterƒvaluesƒinƒallƒfieldsƒofƒtheƒNewƒ
DiverƒRegistrationƒform!ƒClickƒyourƒbrowser'sƒBackƒbuttonƒto
returnƒtoƒtheƒpreviousƒpage.</p>");
7. Add the following statements to the end of the script section to connect to
the database server. Replace user and password with the MySQL user-
name and password you created in Chapter 8.
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"user",ƒ"password")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒconnectƒtoƒtheƒdatabaseƒserver.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_connect_errno()
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_connect_error())ƒ.ƒ"</p>";
8. Add the following statements, which create and select the scuba_school
database. The contents of the conditional expression in the if statement only 9
execute if the mysqli_select_db() function returns a value of false,
which means the database does not exist. Because the contents of the if
statement only execute the first time you open the script, the “Successfully
created the database” message only appears once.
$DBNameƒ=ƒ"scuba_school";
ifƒ(!@mysqli_select_db($DBConnect,ƒ$DBName))ƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒDATABASEƒ$DBName";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Successfullyƒcreatedƒtheƒdatabase.</p>";
ƒƒƒƒƒmysqli_select_db($DBConnect,ƒ$DBName);
}
9. Add the following statement to the end of the script section to close the
database connection:
mysqli_close($DBConnect);
10. Save the document as GetDiverID.php in the Chapter directory for Chapter 9.
With the preceding code, if the table already exists in the selected database, you will see
the error code and message shown in Figure 9-11.
Figure 9-11 Error code and message that prints when you attempt to create a table that
already exists
To prevent your code from attempting to create a table that already exists, use a
mysqli_query() function that attempts to select records from the table. If the func-
tion executes successfully and returns a value of true, the table already exists. The fol-
lowing code demonstrates how to check whether a table exists before attempting to
create it:
$DBNameƒ=ƒ"real_estate";
...
$TableNameƒ=ƒ"commercial";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableName";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring);
Working with Databases and Tables 451
ifƒ($QueryResult)
ƒƒƒƒƒechoƒ"<p>Theƒ$TableNameƒtableƒalreadyƒexists!</p>";
elseƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒTABLEƒcommercialƒ(cityƒVARCHAR(25),ƒ
ƒƒƒƒƒstateƒVARCHAR(25),ƒsale_or_leaseƒVARCHAR(25),ƒ
ƒƒƒƒƒtype_of_useƒVARCHAR(40),ƒpriceƒINT,ƒsizeƒINT)";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Successfullyƒcreatedƒtheƒtable.</p>";
}
ƒmysqli_close($DBConnect);
Next, you add code to the GetDiverID.php script that creates the divers table the first
time the script is called. The divers table will use the diverID field as the primary
key.To identify a field as a primary key in MySQL, you include the PRIMARY KEY key-
words when you first define a field with the CREATE TABLE statement. The
AUTO_INCREMENT keyword is often used with a primary key to generate a unique ID
for each new row in a table. The first row in a field that is created with the 9
AUTO_INCREMENT keyword is assigned a value of 1. The value for each subsequently
added row is incremented by 1 from the preceding row. Another keyword that is often
used with primary keys is the NOT NULL keyword, which requires a field to include a
value. As an example, the following SQL statement defines a primary key named id for
the inventory table using the SMALLINT data type. The id field definition also
includes the NOT NULL and AUTO_INCREMENT keywords.
CREATEƒTABLEƒinventoryƒ(idƒSMALLINTƒNOTƒNULLƒAUTO_INCREMENTƒ
PRIMARYƒKEY,ƒmakeƒVARCHAR(25),ƒmodelƒVARCHAR(50),ƒpriceƒFLOAT,ƒ
quantityƒINT);
When you add records to a table that includes an AUTO_INCREMENT field, you specify
NULL as the field value. The following SQL statement inserts a new record into the
inventory table of the guitars database. If this is the first record added to the table,
its primary key will be a value of 1.
INSERTƒINTOƒinventoryƒVALUES(NULL,ƒ'Ovation',ƒ
'1777ƒLXƒLegend',ƒ1049.00,ƒNULL);
Next, you add code to the GetDiverID.php script that creates the divers table the first
time the script is called. The divers table includes an autoincrementing primary key.
To add code to the GetDiverID.php script that creates the divers table the first time
the script is called:
1. Return to the GetDiverID.php document in your text editor.
452 Chapter 9 Manipulating MySQL Databases with PHP
MANIPULATING RECORDS
In this section, you learn how to use PHP to add, update, and delete database records.
To delete records in a table, you use the DELETE and WHERE keywords with the
mysqli_query() function. Remember that the WHERE keyword determines which
records to delete in the table. For example, the following statement deletes the “Taylor
210 Dreadnought” record from the inventory table in the guitars database:
$SQLstringƒ=ƒ"DELETEƒFROMƒinventoryƒWHEREƒmake='Taylor'ƒ
ƒƒƒƒƒANDƒmodel='210ƒDreadnought'";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<p>Successfullyƒdeletedƒtheƒrecords.</p>";
To delete all the records in a table, omit the WHERE keyword. For example, the follow-
ing statement deletes all the records in the inventory table:
$SQLstringƒ=ƒ"DELETEƒFROMƒinventory";
Next, you add code to the GetDiverID.php script that adds a new diver record to the
divers table in the scuba_school database. You also use the
mysqli_insert_id() function, which returns the ID created with AUTO_INCRE-
MENT in the last INSERT operation.You pass to the mysqli_insert_id() function
the variable to which you assigned the database connection with the mysqli_con-
nect() function. The mysqli_insert_id() function is useful when you need to
find the primary key created for new records you add to a database table.
To add code to the GetDiverID.php script that adds a new diver record to the divers
table in the scuba_school database:
1. Return to the GetDiverID.php document in your text editor.
2. Add the following statements above the mysqli_close() statement to
copy the values that were passed from the form in the Registration.html to
PHP variables:
$Firstƒ=ƒaddslashes($_GET['first_name']);
$Lastƒ=ƒaddslashes($_GET['last_name']);
$Phoneƒ=ƒaddslashes($_GET['phone']);
$Addressƒ=ƒaddslashes($_GET['address']);
$Cityƒ=ƒaddslashes($_GET['city']);
$Stateƒ=ƒaddslashes($_GET['state']);
$Zipƒ=ƒaddslashes($_GET['zip']);
$Emailƒ=ƒaddslashes($_GET['email']);
Manipulating Records 455
9. Click your browser’s Back button, enter some new values in the New Diver
Registration form, and then click the Get Diver ID button. The new diver
ID should be 2. Notice that the messages about successfully creating the data-
base and divers table do not appear this time.
10. Close your Web browser window.
Next, you create the CourseListings.php script, which divers can use to register for
classes.
To create the CourseListings.php script:
1. Create a new document in your text editor.
2. Type the <!DOCTYPE> declaration, <html> element, header information,
and <body> element. Use the strict DTD and “Course Listings” as the con-
tent of the <title> element.
3. Add the following <link> element above the closing </head> tag to link
to the php_styles.css style sheet in your Chapter directory:
<linkƒrel="stylesheet"ƒhref="php_styles.css"ƒtype="text/css"ƒ/>
6. Add the following statements to the script section to connect to the database
server and open the scuba_school database. Replace user and password
with the MySQL username and password you created in Chapter 8.
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"user",ƒ"password")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒconnectƒtoƒtheƒdatabaseƒserver.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_connect_errno()
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_connect_error())ƒ.ƒ"</p>";
$DBNameƒ=ƒ"scuba_school";
@mysqli_select_db($DBConnect,ƒ$DBName)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒselectƒtheƒdatabase.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
7. Add the following statements to the end of the script section to ensure that
users open the page with a valid diver ID:
$DiverIDƒ=ƒ$_GET['diverID'];
ifƒ(empty($DiverID))
ƒƒƒƒƒexit("<p>YouƒmustƒenterƒaƒdiverƒID!ƒClickƒyourƒbrowser'sƒ
Backƒbuttonƒtoƒreturnƒtoƒtheƒpreviousƒpage.</p>");
$TableNameƒ=ƒ"divers";
9
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableNameƒWHEREƒdiverID='$DiverID'";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ifƒ(mysqli_num_rows($QueryResult)ƒ==ƒ0)
ƒƒƒƒƒdie("<p>YouƒmustƒenterƒaƒvalidƒdiverƒID!ƒClickƒyourƒ
browser'sƒBackƒbuttonƒtoƒreturnƒtoƒtheƒRegistrationƒform.</p.");
8. Add the following statement to the end of the script section to close the
database connection:
mysqli_close($DBConnect);
9. Add the following form to the end of document body. This form allows
divers to review their current schedule with the ReviewSchedule.php script.
<formƒmethod="get"ƒaction="ReviewSchedule.php">
<p><strong>StudentƒID:ƒ<?=ƒ$DiverIDƒ?></strong>
<inputƒtype="submit"ƒvalue="ƒReviewƒCurrentƒScheduleƒ"ƒ/><inputƒ
type="hidden"ƒname="diverID"ƒvalue="<?=ƒ$DiverIDƒ?>"ƒ/></p>
</form>
458 Chapter 9 Manipulating MySQL Databases with PHP
10. Add the following form to the end of document body. This is the form divers
use to register for classes with the RegisterDiver.php script.
<formƒmethod="get"ƒaction="RegisterDiver.php">
<p><strong>Selectƒtheƒclassƒyouƒwouldƒlikeƒtoƒtake:</strong><brƒ/>
<inputƒtype="radio"ƒname="class"ƒvalue="BeginningƒOpenƒWater"ƒ
checked="checked"ƒ/>BeginningƒOpenƒWater<brƒ/>
<inputƒtype="radio"ƒname="class"ƒvalue="AdvancedƒOpenƒWater"ƒ/>
AdvancedƒOpenƒWater<brƒ/>
<inputƒtype="radio"ƒname="class"ƒvalue="RescueƒDiving"ƒ/>
RescueƒDiving<brƒ/>
<inputƒtype="radio"ƒname="class"ƒ
value="DivemasterƒCertification"ƒ/>DivemasterƒCertification<brƒ/>
<inputƒtype="radio"ƒname="class"ƒ
value="InstructorƒCertification"ƒ/>InstructorƒCertification</p>
<p><strong>AvailableƒDaysƒandƒTimes:</strong><brƒ/>
<selectƒname="days">
<optionƒselected="selected"ƒvalue="MondaysƒandƒWednesdays">
MondaysƒandƒWednesdays</option>
<optionƒvalue="TuesdaysƒandƒThursdays">
TuesdaysƒandƒThursdays</option>
<optionƒvalue="WednesdaysƒandƒFridays">
WednesdaysƒandƒFridays</option>
</select>
<selectƒname="time">
<optionƒselected="selected"ƒvalue="9ƒa.m.ƒ-ƒ11ƒa.m.">9ƒa.m.ƒ-ƒ11ƒ
a.m.</option>
<optionƒvalue="1ƒp.m.ƒ-ƒ3ƒp.m.">1ƒp.m.ƒ-ƒ3ƒp.m.</option>
<optionƒvalue="6ƒp.m.ƒ-ƒ8ƒp.m.">6ƒp.m.ƒ-ƒ8ƒp.m.</option>
</select><inputƒtype="hidden"ƒname="diverID"ƒ
value="<?=ƒ$DiverIDƒ?>"ƒ/></p>
<p><inputƒtype="submit"ƒvalue="ƒRegisterƒ"ƒ/>
<inputƒtype="reset"ƒ/></p>
</form>
9
Figure 9-13 Course Listings Web page
13. Leave the Course Listings page open in your Web browser.
Next, you create the RegisterDiver.php script, which adds diver registration informa-
tion to the registration table.
To create the RegisterDiver.php script:
1. Create a new document in your text editor.
2. Type the <!DOCTYPE> declaration, <html> element, header information,
and <body> element. Use the strict DTD and “Register Diver” as the con-
tent of the <title> element.
3. Add the following <link> element above the closing </head> tag to link
to the php_styles.css style sheet in your Chapter directory:
<linkƒrel="stylesheet"ƒhref="php_styles.css"ƒtype="text/css"ƒ/>
4. Add the following heading element to the document body:
<h1>AquaƒDon'sƒScubaƒSchool</h1>
<h2>RegistrationƒConfirmation</h2>
5. Add the following script section to the end of the document body:
<?php
?>
460 Chapter 9 Manipulating MySQL Databases with PHP
6. Add the following statements to the script section to ensure that users open
the page with a valid diver ID:
$DiverIDƒ=ƒ$_GET['diverID'];
ifƒ(empty($DiverID))
ƒƒƒƒƒexit("<p>YouƒmustƒenterƒaƒdiverƒID!ƒClickƒyourƒbrowser'sƒ
Backƒbuttonƒtoƒreturnƒtoƒtheƒpreviousƒpage.</p>");
7. Add the following statements to the end of the script section to connect to
the database server and open the scuba_school database:
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"dongosselin",ƒ
"rosebud")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒconnectƒtoƒtheƒdatabaseƒserver.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_connect_errno()
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_connect_error())ƒ.ƒ"</p>";
$DBNameƒ=ƒ"scuba_school";
@mysqli_select_db($DBConnect,ƒ$DBName)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒselectƒtheƒdatabase.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
8. Add the following statements to the end of the script section to create the
registration table if it does not exist:
$TableNameƒ=ƒ"registration";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableName";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring);
ifƒ(!$QueryResult)ƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒTABLEƒregistrationƒ(diverIDƒSMALLINT,ƒ
classƒVARCHAR(40),ƒdaysƒVARCHAR(40),ƒtimeƒVARCHAR(40))";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒcreateƒtheƒregistrationƒ
table.</p>"
ƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Successfullyƒcreatedƒtheƒregistrationƒtable.</p>";
}
9. Add the following statements to the end of the script section to register the
diver in the selected class:
$Classƒ=ƒ$_GET['class'];
$Daysƒ=ƒ$_GET['days'];
$Timeƒ=ƒ$_GET['time'];
$SQLstringƒ=ƒ"INSERTƒINTOƒ$TableNameƒVALUES('$DiverID',ƒ'$Class',ƒ
ƒƒƒƒƒ'$Days',ƒ'$Time')";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
Manipulating Records 461
10. Add the following statement to the end of the script section to close the
database connection:
mysqli_close($DBConnect);
11. Finally, add the following text and elements to the end of the document body:
<p>Youƒareƒregisteredƒforƒ<?=ƒ"$Classƒonƒ$Days,ƒ$Time"ƒ?>.ƒClickƒ
yourƒbrowser'sƒBackƒbuttonƒtoƒregisterƒforƒanotherƒcourseƒorƒ
reviewƒyourƒschedule.</p>
14. Click your browser’s Back button to return to the Course Listings page.
The last script you create is the ReviewSchedule.php script, which allows divers to
review the classes in which they are registered.
To create the ReviewSchedule.php script:
1. Create a new document in your text editor.
2. Type the <!DOCTYPE> declaration, <html> element, header information,
and <body> element. Use the strict DTD and “Review Schedule” as the
content of the <title> element.
462 Chapter 9 Manipulating MySQL Databases with PHP
3. Add the following <link> element above the closing </head> tag to link
to the php_styles.css style sheet in your Chapter directory:
<linkƒrel="stylesheet"ƒhref="php_styles.css"ƒtype="text/css"ƒ/>
7. Add the following statements to the end of the script section to connect to the
database server and open the scuba_school database. Replace user and
password with the MySQL username and password you created in Chapter 8.
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"user",ƒ"password")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒconnectƒtoƒtheƒdatabaseƒserver.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_connect_errno()
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_connect_error())ƒ.ƒ"</p>";
$DBNameƒ=ƒ"scuba_school";
@mysqli_select_db($DBConnect,ƒ$DBName)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒselectƒtheƒdatabase.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
8. Add the following statements to the end of the script section to query the
database for all records that match the diver ID:
$TableNameƒ=ƒ"registration";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableNameƒWHEREƒdiverID='$DiverID'";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
9. Next, add the following statements to the end of the script section, which
print a message if the diver has not yet registered for any classes:
ifƒ(mysqli_num_rows($QueryResult)ƒ==ƒ0)
ƒƒƒƒƒdie("<p>Youƒhaveƒnotƒregisteredƒforƒanyƒclasses!ƒClickƒyourƒ
ƒƒƒƒƒbrowser'sƒBackƒbuttonƒtoƒreturnƒtoƒtheƒpreviousƒpage.</p>");
Manipulating Records 463
10. Add the following statements to the end of the script section to print the
results in an HTML table:
echoƒ"<tableƒwidth='100%'ƒborder='1'>";
echoƒ"<tr><th>Class</th><th>Days</th>
<th>Time</th></tr>";
$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
doƒ{
ƒƒƒƒƒechoƒ"<tr><td>{$Row['class']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['days']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['time']}</td></tr>";
ƒƒƒƒƒ$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
}ƒwhileƒ($Row);
11. Finally, add the following statements to the end of the script section to close
the database connection and the query results:
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
12. Save the document as ReviewSchedule.php in the Chapter directory for
Chapter 9, and then close it in your text editor. 9
13. Return to the Course Listings page in your Web browser and register for
several other classes. After you have registered for a few classes, click the
Review Current Schedule button to display your schedule. Figure 9-15
shows the Review Schedule Web page for a diver who is signed up for three
classes.
$SQLstringƒ=ƒ"DELETEƒFROMƒinventoryƒWHEREƒmake='Washburn'";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<p>Successfullyƒdeletedƒ"ƒ
ƒƒƒƒƒ.ƒmysqli_affected_rows($DBConnect)ƒ.ƒ"ƒrecord(s).</p>";
Figure 9-17 Output of mysqli_info() function for an INSERT query that adds multiple
records
The mysqli_info() function also returns information for LOAD DATA queries. The
following statements print the output shown in Figure 9-18:
$SQLstringƒ=ƒ"LOADƒDATAƒLOCALƒINFILEƒ'c:/temp/inventory.txt'ƒ
ƒƒƒƒƒINTOƒTABLEƒinventory;";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<p>Successfullyƒaddedƒtheƒrecords.</p>";
echoƒ"<p>"ƒ.ƒmysqli_info($DBConnect)ƒ.ƒ"</p>";
Chapter Summary 467
CHAPTER SUMMARY
❐ The mysqli_connect() function opens a connection to a MySQL database
server.
9
❐ The mysqli_close() function closes a database connection.
❐ The mysqli_select_db() function selects a database.
❐ Writing code that anticipates and handles potential problems is often called bullet-
proofing.
❐ The error control operator (@) suppresses error messages.
❐ The die() and exit() functions terminate script execution.
❐ The mysqli_connect_errno() function returns the error code from the last
database connection attempt or zero if no error occurred.
❐ The mysqli_connect_error() function returns the error message from the last
database connection attempt or an empty string if no error occurred.
❐ The mysqli_errno() function returns the error code from the last attempted
MySQL function call or zero if no error occurred.
❐ The mysqli_error() function returns the error message from the last attempted
MySQL function call or an empty string if no error occurred.
❐ The mysqli_query() function sends SQL statements to MySQL.
❐ A result pointer is a special type of variable that refers to the currently selected row
in a resultset.
❐ The mysqli_fetch_row() function returns the fields in the current row of a
resultset into an indexed array and moves the result pointer to the next row.
❐ The mysqli_fetch_assoc() function returns the fields in the current row of a
resultset into an associative array and moves the result pointer to the next row.
468 Chapter 9 Manipulating MySQL Databases with PHP
REVIEW QUESTIONS
1. MySQL support is enabled in PHP by default. True or False?
2. Which of the following functions closes a database connection?
a. close()
b. mysqli_close()
c. mysqli_free()
d. mysqli_free_connect()
Review Questions 469
10. Which of the following functions reports the error message from the last failed
database connection attempt?
a. mysqli_connect_errno()
b. mysqli_connect_error()
c. mysqli_errno()
d. mysqli_error()
11. Explain what a result pointer is and how to create and use one.
12. Which of the following functions returns the fields in the current row of a result-
set into an indexed array?
a. mysqli_data_fetch()
b. mysqli_data_seek()
c. mysqli_index_row()
d. mysqli_fetch_row()
13. Which of the following functions returns the fields in the current row of a result-
set into an associative array?
a. mysqli_assoc_fetch()
b. mysqli_fetch_keys()
c. mysqli_fetch_assoc()
d. mysqli_fetch_index()
14. Write a simple code segment that demonstrates how to use the
mysqli_num_rows() and mysqli_num_fields() functions to determine
whether a SQL query returned results.
15. Which of the following functions closes a resultset to ensure that it doesn’t keep
taking up space in your computer’s memory?
a. mysqli_free_result()
b. mysqli_result_close()
c. mysqli_free()
d. mysqli_close_result()
16. Write a simple code segment that demonstrates how to use the
mysqli_db_select() function to check whether a database exists before you
create or delete it.
17. Write a simple code segment that demonstrates how to use a mysqli_query()
function to prevent your code from attempting to create a table that already exists.
Hands-On Projects 471
HANDS-ON PROJECTS
Hands-On Project 9-1
In this project, you create a hit counter script that keeps track of the number of hits a
Web page receives.The number of hits will be stored as autoincrementing primary keys
in MySQL.
1. Create a new document in your text editor and type the <!DOCTYPE> declara-
tion, <html> element, document head, and <body> element. Use the strict DTD
and “Hit Counter” as the content of the <title> element.
2. Add the following script section to the document body:
<?php
?>
3. Add the following statement to the script section to connect to the database.
Replace user and password with the MySQL username and password you created
in Chapter 8.
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"user",ƒ"password")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒconnectƒtoƒtheƒdatabaseƒserver.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_connect_errno()
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_connect_error())ƒ.ƒ"</p>";
472 Chapter 9 Manipulating MySQL Databases with PHP
4. Add the following statements to the end of the script section to create a database
named hit_counter if it does not already exist:
$DBNameƒ=ƒ"hit_counter";
ifƒ(!@mysqli_select_db($DBConnect,ƒ$DBName))ƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒDATABASEƒ$DBName";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Youƒareƒtheƒfirstƒvisitor!</p>";
ƒƒƒƒƒmysqli_select_db($DBConnect,ƒ$DBName);
}
5. Add the following statements to the end of the script section to create a table
named count if it does not already exist. The table consists of a single autoincre-
menting primary key field named countID.
$TableNameƒ=ƒ"count";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableName";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring);
ifƒ(!$QueryResult)ƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒTABLEƒ$TableNameƒ(countIDƒSMALLINTƒNOTƒ
NULLƒAUTO_INCREMENTƒPRIMARYƒKEY)";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒcreateƒtheƒtable.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
}
6. Add the following statements to the end of the script section to add a new row to
the count table, which increments the countID field by one:
$SQLstringƒ=ƒ"INSERTƒINTOƒ$TableNameƒVALUES(NULL)";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
7. Finally, add the following statements to the end of the script section. The first
statement uses the mysqli_insert_id() function to return the last value
assigned to the countID field and the echo() statement prints the number of
hits. The last statement closes the database connection.
$Hitsƒ=ƒmysqli_insert_id($DBConnect);
echoƒ"<h1>Thereƒhaveƒbeenƒ$Hitsƒhitsƒtoƒthisƒpage!</h1>";
mysqli_close($DBConnect);
8. Save the document as HitCounter.php in the Projects directory for Chapter 9.
Hands-On Projects 473
8. Add the following statements to the end of the script section to create a database
named hit_counter if it does not already exist:
$DBNameƒ=ƒ"guestbook";
ifƒ(!@mysqli_select_db($DBConnect,ƒ$DBName))ƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒDATABASEƒ$DBName";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Youƒareƒtheƒfirstƒvisitor!</p>";
ƒƒƒƒƒmysqli_select_db($DBConnect,ƒ$DBName);
}
9. Add the following statements to the end of the script section to create a table
named count if it does not already exist. The table consists of a single autoincre-
menting primary key field named countID.
$TableNameƒ=ƒ"visitors";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableName";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring);
ifƒ(!$QueryResult)ƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒTABLEƒ$TableNameƒ(countIDƒSMALLINTƒ
ƒƒƒƒƒNOTƒNULLƒAUTO_INCREMENTƒPRIMARYƒKEY,ƒ
ƒƒƒƒƒlast_nameƒVARCHAR(40),ƒfirst_nameƒVARCHAR(40))";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒcreateƒtheƒtable.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect)) .ƒ"</p>";
}
10. Finally, add the following statements to the end of the script section. These
mysqli_query() statements add the visitor to the database and the last state-
ment closes the database connection.
$LastNameƒ=ƒaddslashes($_GET['last_name']);
$FirstNameƒ=ƒaddslashes($_GET['first_name']);
$SQLstringƒ=ƒ"INSERTƒINTOƒ$TableNameƒVALUES(NULL,ƒ'$LastName',ƒ
ƒƒƒƒƒ'$FirstName')";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<h1>Thankƒyouƒforƒsigningƒourƒguestƒbook!</h1>";
mysqli_close($DBConnect);
Hands-On Projects 475
6. Add the following statements to the end of the script section to print the records
returned from the visitors table:
echoƒ"<p>Theƒfollowingƒvisitorsƒhaveƒsignedƒourƒguestƒbook:</p>";
echoƒ"<tableƒwidth='100%'ƒborder='1'>";
echoƒ"<tr><th>FirstƒName</th><th>LastƒName</th></tr>";
$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
doƒ{
ƒƒƒƒƒechoƒ"<tr><td>{$Row['first_name']}</td>";
ƒƒƒƒƒechoƒ"<td>{$Row['last_name']}</td></tr>";
ƒƒƒƒƒ$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
}ƒwhileƒ($Row);
7. Add the following statements to the end of the script section to close the database
connection and the result pointer:
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
8. Save the document as ShowGuestBook.php in the Projects directory for
Chapter 9.
9. Return to the GuestBook.html document in your text editor and add the fol-
lowing text and elements to the end of the document body:
<p><aƒhref="ShowGuestBook.php">ShowƒGuestƒBook</a></p>
10. Save the GuestBook.html file, and then open it in your Web browser by enter-
ing the following URL:
http://localhost/PHP_Projects/Chapter.09/Projects/GuestBook.html.
Click the Show Guest Book link to see if the script functions correctly.
11. Close your Web browser window.
CASE PROJECTS
In Chapter 6, you created versions of the following projects that saved data to text files.
Create new versions of each project that store data in MySQL databases instead of text
files. Save the documents you create for the following projects in the Cases directory for
Chapter 9.