0% found this document useful (0 votes)
15 views

PHP Chapter 9

Uploaded by

arasivedhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

PHP Chapter 9

Uploaded by

arasivedhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

CHAPTER

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

O ne of PHP’s greatest strengths is its ability to access and manipulate databases.


With its strong ODBC support, you can use PHP to access any database that
is ODBC compliant. PHP also includes functionality that allows you to work
directly with different types of databases, without going through ODBC. Some of
the databases that you can access directly from PHP include Oracle, Informix,
PostgresSQL, and MySQL.
PHP also supports other methods of accessing data sources, including
SQLite, database abstraction layer functions, and PEAR DB. SQLite and
database abstraction layer functions work with file-based databases instead of
server-based databases such as MySQL.The PHP Extension and Application
Repository (PEAR) is a library of open source PHP code. One of the most
popular PEAR code modules is PEAR DB, which simplifies access between
PHP and a database server by providing a generic interface that works with
various types of database systems, similar to the way ODBC works.Although
PEAR DB and ODBC perform similar functions, the difference between
the two languages is that PEAR is designed specifically to work with PHP,
whereas ODBC is a more generic protocol that is used by many program-
ming languages and database management systems.
With so many database connectivity options, how do you decide which
method to use for accessing databases with PHP? First, you need to select a
database management system. If you are new to database development, you
should probably start with an open source database such as PostgresSQL or

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.

CONNECTING TO MYSQL WITH PHP


As you work through this chapter, keep in mind that almost everything you learned in
the preceding chapter about MySQL is applicable to this chapter. Although you need to
learn a few new functions to access MySQL with PHP, you will execute the same SQL
statements that you used with the MySQL Monitor.The great benefit to using PHP or
some other server-side scripting language to read from and write to a database server is
that it allows you to create a Web-based interface that makes it much easier for visitors
to interact with your database.
Before you can use PHP to read from and write to MySQL databases, you need to enable
MySQL support in PHP and learn how to connect to the MySQL database server.

Enabling MySQL Support in PHP


In PHP versions earlier than PHP 5, support for MySQL was installed by default.
However, starting with PHP 5, MySQL support no longer comes preinstalled with PHP.
To enable MySQL support in PHP, you must configure your PHP installation to use the
mysqli extension.

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.

To enable MySQL support on Windows installations of PHP:


1. Start your Web browser, and enter the Web address for the PHP download
page: http://www.php.net/downloads.php. Download the Windows zip
package (not the Windows binary installer) containing the most recent
Windows binary files. Save the file to a temporary folder on your computer.
2. Open Windows Explorer or My Computer and navigate to the folder
where you downloaded the Windows zip package. Double-click the file to
open it in WinZip, which is the archive utility for Windows.
3. Extract the libmysql.dll and php_mysqli.dll files to the directory where
you installed PHP. By default, the PHP installation directory is C:\PHP. To
extract individual files in WinZip, locate and click on a filename, and then
click the Extract button. The Extract dialog box opens, which allows you to
specify the location where you want to store the file.
4. Close WinZip.
422 Chapter 9 Manipulating MySQL Databases with PHP

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.

See Chapter 2 for information on how to restart your Web server.

Opening and Closing a MySQL Connection


Before you can use PHP to access the records in a database, you must first use the
mysqli_connect() function to open a connection to a MySQL database server.
Opening a connection to a database is similar to opening a handle to a text file, as you
did in Chapter 6. However, instead of returning a file handle, the mysqli_connect()
function returns a positive integer if it connects to the database successfully or false if it
doesn’t.You assign the return value from the mysqli_connect() function to a vari-
able that you can use to access the database in your script. The basic syntax for the
mysqli_connect() function is as follows:
$connectionƒ=ƒmysqli_connect("host"[,ƒ"userƒ",ƒ"password",ƒ"database"])

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

To change users after connecting to a database, use the mysqli_change_


user() function.

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.

Table 9-1 MySQL server information functions


Function Description
mysqli_get_client_info() Returns the MySQL client version
mysqli_get_client_version() Returns the MySQL client version as an
integer
mysqli_get_host_info(connection) Returns the MySQL database server
connection information
mysqli_get_proto_info(connection) Returns the MySQL protocol version
mysqli_get_server_info(connection) Returns the MySQL database server version
mysqli_get_server_version(connection) Returns the MySQL database server version
as an integer

The mysqli_get_client_info() and mysqli_get_client_


version() functions do not accept any arguments. However, you must pass
the variable representing the database connection to the rest of the functions
listed in Table 9-1.

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"ƒ/>

4. Add the following heading element to the document body:


<h1>MySQLƒDatabaseƒServerƒInformation</h1>
5. Add the following script section to the end of the document body:
<?php
?>
6. Add the following mysqli_connect() statement to the script section.
Replace user and password with the MySQL username and password you
created in Chapter 8.
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"user",ƒ"password");
7. Add to the end of the script section the following statements, which print
information about your installation of MySQL server:
echoƒ"<p>MySQLƒclientƒversion:ƒ"ƒ
ƒƒƒƒƒ.ƒmysqli_get_client_info()ƒ.ƒ"</p>";
echoƒ"<p>MySQLƒconnection:ƒ"ƒ
ƒƒƒƒƒ.ƒmysqli_get_host_info($DBConnect)ƒ.ƒ"</p>";
echoƒ"<p>MySQLƒprotocolƒversion:ƒ"ƒ
ƒƒƒƒƒ.ƒmysqli_get_proto_info($DBConnect)ƒ.ƒ"</p>";
echoƒ"<p>MySQLƒserverƒversion:ƒ"ƒ
ƒƒƒƒƒ.ƒmysqli_get_server_info($DBConnect)ƒ.ƒ"</p>";
8. Finally, add the following statement to the end of the script section to close
the database connection:
mysqli_close($DBConnect);
9. Save the document as MySQLInfo.php in the Chapter directory for
Chapter 9, and then close it in your text editor.
10. Open the MySQLInfo.php file in your Web browser by entering the fol-
lowing URL: http://localhost/PHP_Projects/Chapter.09/Chapter/
MySQLInfo.php.Your Web browser should appear similar to Figure 9-1,
although the information printed from each function might be different for
your MySQL installation.
Connecting to MySQL with PHP 425

Figure 9-1 MySQLInfo.php in a Web browser

11. Close your Web browser window.


9
Selecting a Database
As you saw in Chapter 6, you must first select a database with the use database state-
ment when you log on to the MySQL Monitor. Although you can select a database by
passing a database name as the fourth argument to the mysqli_connect() function, you
can also select or change a database with the mysqli_select_db() function.The syn-
tax for the mysqli_select_db() function is mysqli_select_db(connection,
database). The function returns a value of true if it successfully selects a database or
false if it doesn’t. For example, instead of selecting a database by passing the database
name as the fourth argument to the mysqli_connect() function, the following code
uses a mysqli_select_db() statement to open the real_estate database from the
$DBConnect database connection:
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"dongosselin",ƒ"rosebud");
mysqli_select_db($DBConnect,ƒ"real_estate");
//ƒadditionalƒstatementsƒthatƒaccessƒorƒmanipulateƒtheƒdatabase
mysqli_close($DBConnect);

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"ƒ/>

4. Add the following heading element to the document body:


<h1>FlightlogƒEntries</h1>
5. Add the following script section to the end of the document body:
<?php
?>
6. Add the following mysqli_connect() statement to the script section.
Replace user and password with the MySQL username and password you cre-
ated in Chapter 8.
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"user",ƒ"password");
7. After the mysqli_connect() function, add the following statements to
select the flightlog database:
$DBNameƒ=ƒ"flightlog";
mysqli_select_db($DBConnect,ƒ$DBName);
8. Add the following statement to the end of the script section to close the
database connection:
mysqli_close($DBConnect);
9. Save the document as FlightlogEntries.php in the Chapter directory for
Chapter 9, and then close it in your text editor.

HANDLING MYSQL ERRORS


When accessing MySQL databases and other types of data sources, you need to under-
stand the errors that can affect the execution of your script. One of the most important
errors that you need to consider occurs when you cannot connect to a database server.
Reasons that you may not be able to connect to a database server include the following:
■ The database server is not running.
■ You do not have sufficient privileges to access the data source.
■ You entered an invalid username and/or password.
When it comes to connecting to a database server or selecting a database, your first
instinct might be to check the value that is returned from the mysqli_connect()
function and mysqli_select_db() function. The mysqli_connect() function
returns a positive integer if it connects to the database successfully or false if it doesn’t.
Thus, you might make the mistake of trying to use the return value to determine if the
connection is successful. As an example, consider the following code. The conditional
Handling MySQL Errors 427

expression in the if statement uses the Not operator (! ) to determine if the


$DBConnect variable is equal to false. If the variable is equal to false, a message prints
to the Web browser informing the user that the database server is not available. If the
variable is not equal to false, a message prints to the Web browser informing the user
that she connected successfully to the database server.
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"dongosselin",ƒ
ƒƒƒƒƒ"rosebud",ƒ"flightlog");
ifƒ(!$DBConnect)
ƒƒƒƒƒƒechoƒ"<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</p>";
elseƒƒƒ{
ƒƒƒƒƒechoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
ƒƒƒƒƒ//ƒadditionalƒstatementsƒthatƒaccessƒtheƒdatabaseƒserver
ƒƒƒƒƒmysqli_close($DBConnect);
}

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.

Figure 9-2 Database connection error message

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

Figure 9-3 FlightlogEntries.php in a Web browser

4. Close your Web browser window.

Suppressing Errors with the Error Control Operator 9


Although standard error messages that are generated by programming languages such as
PHP are very helpful to programmers, they tend to scare users, who might think that
they somehow caused the error. Errors can and will occur, but you should never let your
users think that they did something wrong.Your goal should be to write code that antic-
ipates any problems that may occur and includes graceful methods of dealing with those
problems. Writing code that anticipates and handles potential problems is often called
bulletproofing. One bulletproofing technique you have already used has to do with val-
idating submitted form data. For example, in Chapter 5, you saw the following code,
which ensures that values submitted to a script that measures body mass contain numeric
values. This example contains a nested if statement that tests whether the
$_GET['height'] and $_GET['weight'] variables are numeric after the first if
statement checks to see whether they are set.
ifƒ(isset($_GET['height'])ƒ&&ƒisset($_GET['weight']))ƒ{
ƒƒƒƒƒifƒ(!is_numeric($_GET['weight'])ƒ||ƒ!is_numeric($_GET['height']))ƒ{
ƒƒƒƒƒƒƒƒƒƒ$BodyMassƒ=ƒ$_GET['weight']ƒ/ƒ($_GET['height']ƒ
ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ*ƒ$_GET['height'])ƒ*ƒ703;
ƒƒƒƒƒƒƒƒƒƒprintf("<p>Yourƒbodyƒmassƒindexƒisƒ%d.</p>",ƒ
ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ$BodyMass);
ƒƒƒƒƒ}
ƒƒƒƒƒelse
ƒƒƒƒƒƒƒƒƒƒechoƒ"<p>Youƒmustƒenterƒnumericƒvalues!</p>";
}

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

sources such as the mysqli_connect() and mysqli_select_db() functions. Using


the error control operator to suppress error messages does not mean you can then ignore
errors that may occur. Instead, the error control operator allows you to provide a more
graceful way of handling an error instead of allowing an intimidating error message to
be printed to the Web browser. The following example contains a modified version of
the code that connects with a username and password of “dongosselin” and “rosebud”
to the flightlog database. In this example, both the mysqli_connect() and
mysqli_select_db() functions are preceded by error control operators to suppress
any error messages that may occur.
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"dongosselin",ƒ"rosebud");
ifƒ(!$DBConnect)
ƒƒƒƒƒƒechoƒ"<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</p>";
elseƒƒƒ{
ƒƒƒƒƒƒ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);
}

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.

Terminating Script Execution


Up to this point in this book, you have relied on if...else statements to execute code
only when certain conditions have been met. For example, the else clause in the pre-
ceding example executes only if the mysqli_connect() successfully connects to a
database server.The else clause also contains a nested if statement, which executes only
Handling MySQL Errors 431

if the mysqli_select_db() function successfully opens a database. Instead of relying


on if...else statements to execute code, you can more easily terminate script execu-
tion with the die() or exit() functions. The die() and exit() functions perform
the same task of terminating script execution, although the die() version is usually used
when attempting to access a data source. Both functions accept a single string argument,
which is printed to the Web browser when the script ends.You can call the die() and
exit() functions as separate statements or by appending either function to an expres-
sion with the Or operator.The following code demonstrates how to call the die() func-
tion by using if statements. Notice that the code does not require else clauses because
the script terminates when the conditional expressions in the if statements are true.
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"root",ƒ"paris");
ifƒ(!$DBConnect)
ƒƒƒƒƒdie("<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</p>");
echoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
$DBSelectƒ=ƒ@mysqli_select_db($DBConnect,ƒ"flightlog");
ifƒ(!$DBSelect)
ƒƒƒƒƒdie("<p>Theƒdatabaseƒisƒnotƒavailable.</p>");
echoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</p>";
//ƒadditionalƒstatementsƒthatƒaccessƒtheƒdatabase
9
mysqli_close($DBConnect);
The following code demonstrates how to use an Or operator to append the die() func-
tion to the statements that call the mysqli_connect() and mysqli_select_db()
functions:
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"dongosselin",ƒ
"rosebud")
ƒƒƒƒƒOrƒdie("<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</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ƒserver
mysqli_close($DBConnect);
Next, you modify the mysqli_connect() and mysqli_select_db() functions in
the FlightlogEntries.php script so they use die() functions to terminate the script in
the event of an error.
432 Chapter 9 Manipulating MySQL Databases with PHP

To modify the mysqli_connect() and mysqli_select_db() functions in the


FlightlogEntries.php script so they use die() functions to terminate the script in the
event of an error:
1. Return to the FlightlogEntries.php document in your text editor.
2. Modify the contents of the script section so it uses die() functions to ter-
minate the script in the event of an error.Your modified script section should
appear as follows:
$DBConnectƒ=ƒ@mysqli_connect("localhost",ƒ"user",ƒ"password")
ƒƒƒƒƒOrƒdie("<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</p>");
echoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
$DBNameƒ=ƒ"flightlog";
@mysqli_select_db($DBConnect,ƒ$DBName)
ƒƒƒƒƒOrƒdie("<p>Theƒdatabaseƒisƒnotƒavailable.</p>");
echoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</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. The Web page should appear
the same as it did before you added the error control operators.
4. Close your Web browser window.

Reporting MySQL Errors


The preceding section emphasized the importance of using the error control operator
to prevent PHP from spitting out errors wherever they occur. However, that does not
mean error messages are useless. In fact, when displayed correctly, error numbers and
codes can be invaluable in providing useful feedback and in helping you track down
problems with your script or database. PHP includes the functions listed in Table 9-2 for
reporting MySQL error numbers and codes.

Table 9-2 MySQL error reporting functions


Function Description
mysqli_connect_errno() Returns the error code from the last database connection
attempt or zero if no error occurred
mysqli_connect_error() Returns the error message from the last database connec-
tion attempt or an empty string if no error occurred
mysqli_errno(connection) Returns the error code from the last attempted MySQL
function call or zero if no error occurred
mysqli_error(connection) Returns the error message from the last attempted MySQL
function call or an empty string if no error occurred
mysqli_sqlstate(connection) Returns a string of five characters representing an error
code from the last MySQL operation or 00000 if no error
occurred
Handling MySQL Errors 433

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

The mysqli_connect_errno() and mysqli_connect_error() functions only


report errors that occur when you attempt to connect to a MySQL database server with
the mysqli_connect()function.To obtain error information for any other functions
that access a MySQL database, such as the mysqli_select_db() function, you use
the mysqli_errno() and the mysqli_error() functions. Unlike the
mysqli_connect_errno() and the mysqli_connect_error() functions, you
pass to the the mysqli_errno() and the mysqli_error() functions the variable
representing the database connection.The following example demonstrates how to dis-
play error codes and messages that may occur when you call the
mysqli_select_db() function:
$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,ƒ"flightplan")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒselectƒtheƒdatabase.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</p>";
//ƒadditionalƒstatementsƒthatƒaccessƒtheƒdatabase
mysqli_close($DBConnect);
The preceding script attempts to select a database named flightplan. Figure 9-5
shows the output in a Web browser if the flightplan database does not exist on the
MySQL database server.
Handling MySQL Errors 435

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

EXECUTING SQL STATEMENTS


In this section, you learn how to use PHP to submit SQL statements to MySQL. As
you work through the rest of this chapter, you should recognize the SQL statements
because you worked with all of them in Chapter 8. The primary difference is that
instead of manually executing SQL statements by typing them in the MySQL Monitor
as you did in Chapter 8, you use PHP statements to access MySQL and execute SQL
statements for you.
In PHP, you use the mysqli_query() function to send SQL statements to MySQL.
The mysqli_query() function is the workhorse of PHP connectivity with MySQL;
almost every SQL command you send to MySQL from PHP is executed with the
mysqli_query() function. The basic syntax for the mysqli_query() function is
mysqli_query(connection, query). The mysqli_query() function returns
one of three values, depending on the type of query executed. For SQL statements that
do not return results, such as the CREATE DATABASE and CREATE TABLE statements,
the mysqli_query() function returns a value of true if the statement executes suc-
cessfully. For SQL statements that return results, such as SELECT and SHOW statements,
the mysqli_query() function returns a result pointer that represents the query results.
A result pointer is a special type of variable that refers to the currently selected row in
a resultset. The query pointer is a way of keeping track of where you are in a resultset.
You assign the result pointer to a variable, which you can use to access the resultset in
PHP. The mysqli_query() function returns a value of false for any SQL statements
that fail, regardless of whether they return results. As an example, the following code
queries the guitars database you saw in Chapter 8. The code then executes the
mysqli_query() function and assigns the result pointer to a variable named
$QueryResult.
@mysqli_select_db($DBConnect,ƒ"guitars")
ƒƒƒƒƒOrƒdie("<p>Unableƒtoƒselectƒtheƒdatabase.</p>"
ƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
echoƒ"<p>Successfullyƒopenedƒtheƒdatabase.</p>";
$SQLstringƒ=ƒ"SELECTƒmodel,ƒquantityƒFROMƒinventory";
$QueryResultƒ=ƒmysqli_query($DBConnect,ƒ$SQLstring)
mysqli_close($DBConnect);
You use the same techniques to handle errors with the mysqli_query() function that
you use with the mysqli_connect() and mysqli_select_db() functions. For
example, the following code uses the error control operator to suppress errors and ter-
minates the script with the die() function if the query is unsuccessful. The example
also uses the mysqli_errno() and mysqli_error() functions to report the error
code and message.
$SQLstringƒ=ƒ"SELECTƒmodel,ƒquantityƒFROMƒinventory";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
Executing SQL Statements 437

ƒƒƒƒƒ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

Working with Query Results


Recall that for SQL statements that return results, such as SELECT and SHOW statements,
the mysqli_query() function returns a result pointer that represents the query results.
You assign the result pointer to a variable, which you can use to access the resultset in
PHP.To access the database records through the result pointer, you must use one of the
functions listed in Table 9-3.

Table 9-3 Common PHP functions for accessing database results


Function Description
mysqli_data_seek($Result, position) Moves the result pointer to a specified row
in the resultset
mysqli_fetch_array($Result, Returns the fields in the current row of a
MYSQLI_ASSOC | MYSQLI_NUM | resultset into an indexed array, associative
MYSQLI_BOTH) array, or both and moves the result pointer
to the next row
mysqli_fetch_assoc($Result) Returns the fields in the current row of a
resultset into an associative array and
moves the result pointer to the next row
mysqli_fetch_lengths($Result) Returns the field lengths for the current row
in a resultset into an indexed array
mysqli_fetch_row($Result) Returns the fields in the current row of a
resultset into an indexed array and moves
the result pointer to the next row

First, you learn how to use the mysqli_fetch_row() function to retrieve fields into
an indexed array.

Retrieving Records into an Indexed Array


In Chapter 6, you learned how to use the fgets() function, which returns a line from
a text file and moves the file pointer to the next line.The mysqli_fetch_row() func-
tion is very similar in that it returns the fields in the current row of a resultset into an
indexed array and moves the result pointer to the next row.You can then use the array
to access the individual fields in the row. As an example, the following code prints the
contents of the fields in the first row in the inventory table of the guitars database:
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ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>";
$Rowƒ=ƒmysqli_fetch_row($QueryResult);
Executing SQL Statements 439

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);

Figure 9-6 Output of the inventory table in a Web browser

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);

5. 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 be
similar to Figure 9-7, although you may have added or deleted additional
entries.
Executing SQL Statements 441

Figure 9-7 Output of FlightlogEntries.php with the mysqli_fetch_row() function 9


6. Close your Web browser window.

Retrieving Records into an Associative Array


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.The pri-
mary difference between the mysqli_fetch_assoc() function and the
mysqli_fetch_row() function is that instead of returning the fields into an indexed
array, the mysqli_fetch_assoc() function returns the fields into an associate array
and uses each field name as the array key. For example, the following code uses the
mysqli_fetch_assoc() function to print the contents of the fields in the first row
in the inventory table of the guitars database. Notice that the echo() statements
refer to keys instead of indexes in the $Row[] array.
$Rowƒ=ƒmysqli_fetch_assoc($QueryResult);
echoƒ"<p><strong>Make</strong>:ƒ{$Row['make']}<brƒ/>";
echoƒ"<strong>Model</strong>:ƒ{$Row['model']}<brƒ/>";
echoƒ"<strong>Price</strong>:ƒ{$Row['price']}<brƒ/>";
echoƒ"<strong>Quantity</strong>:ƒ{$Row['quantity']}</p>";
442 Chapter 9 Manipulating MySQL Databases with PHP

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);

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.Your Web page should appear
the same as it did before you modified the code to use
mysqli_fetch_assoc() functions.
5. Close your Web browser window.
Executing SQL Statements 443

Accessing Query Result Information


PHP includes numerous functions for working with query results, including the
mysqli_num_rows() function, which returns the number of rows in a query result,
and the mysqli_num_fields() function, which returns the number of fields in a
query result. Both functions accept a database connection variable as an argument. The
following code demonstrates how to use both functions with the query results returned
from the guitars database. If the number of rows and fields in the query result are not
equal to zero, an echo() statement prints the number of rows and fields. However, if
the number of rows and fields in the query result are equal to zero, an echo() state-
ment prints “Your query returned no results.” Figure 9-8 shows the output if the gui-
tars database contains 10 rows and 4 fields.
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ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ƒexecutedƒtheƒquery.</p>";
$NumRowsƒ=ƒmysqli_num_rows($QueryResult);
9
$NumFieldsƒ=ƒmysqli_num_fields($QueryResult);
ifƒ($NumRowsƒ!=ƒ0ƒ&&ƒ$NumFieldsƒ!=ƒ0)
ƒƒƒƒƒechoƒ"<p>Yourƒqueryƒreturnedƒ"ƒ.ƒ
mysqli_num_rows($QueryResult)ƒ.ƒ"ƒrowsƒandƒ"
ƒƒƒƒƒ.ƒmysqli_num_fields($QueryResult)ƒ.ƒ"ƒfields.</p>";
else
ƒƒƒƒƒechoƒ"<p>Yourƒqueryƒreturnedƒnoƒresults.</p>";
mysqli_close($DBConnect);

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.

Closing Query Results


When you are finished working with query results retrieved with the mysqli_query()
function, you should use the mysqli_free_result() function to close the resultset.
This ensures that the resultset doesn’t keep taking up space in your computer’s memory.
(As you’ll recall, you need to close a database connection for the same reason.) To close
the resultset, pass to the mysqli_free_result() function the variable containing the
result pointer from the mysqli_query() function. The following code uses the
mysqli_free_result() function to close the $QueryResult variable:
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ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ƒexecutedƒtheƒquery.</p>";
...
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
Working with Databases and Tables 445

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.

Next, you add a mysqli_free_result() function to the FlightlogEntries.php script.


To add a mysqli_free_result() function to the FlightlogEntries.php script:
1. Return to the FlightlogEntries.php document in your text editor.
2. Add the following statement above the mysqli_close() statement:
mysqli_free_result($QueryResult);
3. Save the FlightlogEntries.php file and close it in your text editor. Then
open the script 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 the
mysqli_free_result() function.
9
4. Close your Web browser window.

WORKING WITH DATABASES AND TABLES


In this section, you learn how to use PHP to work with MySQL databases and tables.
More specifically, you learn how to create and delete databases and tables. Again, keep
in mind that the SQL statements in this section are identical to the SQL statements you
saw in Chapter 8.The only difference is that they are executed with PHP instead of with
the MySQL Monitor.

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.

Creating and Deleting Databases


You use the CREATE DATABASE statement with the mysqli_query() function to
create a new database.The following statements create a database named real_estate:
$SQLstringƒ=ƒ"CREATEƒDATABASEƒreal_estate";
$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>";
mysqli_close($DBConnect);
446 Chapter 9 Manipulating MySQL Databases with PHP

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

Figure 9-10 Registration.html page in a Web browser

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.

Creating and Deleting Tables


To create a table, you use the CREATE TABLE statement with the mysqli_query()
function. Be sure you have executed the mysqli_select_db() function before exe-
cuting the CREATE TABLE statement or you might create your new table in the wrong
450 Chapter 9 Manipulating MySQL Databases with PHP

database.The following code creates a table named commercial in the real_estate


database.
$DBNameƒ=ƒ"real_estate";
...
$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);

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

2. Add the following variable declarations and mysqli_query() statement to


the end of the script section. The mysqli_query() statement selects all
existing records from the divers table.
$TableNameƒ=ƒ"divers";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableName";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring);
3. Add the following if statement to the end of the script section. The state-
ments in the if statement only execute if the $QueryResult variable con-
tains a value of false, which means that it does not yet exist. Notice that the
CREATE TABLE statement creates the diverID field as an autoincrementing
primary key.
ifƒ(!$QueryResult)ƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"CREATEƒTABLEƒdiversƒ(diverIDƒSMALLINTƒNOTƒ
ƒƒƒƒƒƒƒƒƒƒNULLƒAUTO_INCREMENTƒPRIMARYƒKEY,ƒfirstƒVARCHAR(40),ƒ
ƒƒƒƒƒƒƒƒƒƒlastƒVARCHAR(40),ƒphoneƒVARCHAR(40),ƒ
ƒƒƒƒƒƒƒƒƒƒaddressƒVARCHAR(40),ƒcityƒVARCHAR(40),ƒ
ƒƒƒƒƒƒƒƒƒƒstateƒVARCHAR(2),ƒzipƒVARCHAR(10))";
ƒƒƒƒƒ$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒcreateƒtheƒdiversƒtable.</p>"
ƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
ƒƒƒƒƒechoƒ"<p>Successfullyƒcreatedƒtheƒdiversƒtable.</p>";
}
4. Save the GetDiverID.php document.
To delete a table, you use the DROP TABLE statement with the mysqli_query() func-
tion.The following code demonstrates how to delete the commercial table using sim-
ilar error-handling functionality as the code that created the table:
$DBNameƒ=ƒ"real_estate";
...
$TableNameƒ=ƒ"commercial";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableName";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring);
ifƒ(!$QueryResult)
ƒƒƒƒƒechoƒ"<p>Theƒ$TableNameƒtableƒdoesƒnotƒexist!</p>";
elseƒ{
ƒƒƒƒƒ$SQLstringƒ=ƒ"DROPƒTABLEƒcommercial";
ƒƒƒƒƒ$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ƒtable.</p>";
}
mysqli_close($DBConnect);
Manipulating Records 453

MANIPULATING RECORDS
In this section, you learn how to use PHP to add, update, and delete database records.

Adding, Deleting, and Updating Records


To add records to a table, you use the INSERT and VALUES keywords with the
mysqli_query() function. Remember that the values you enter in the VALUES list
must be in the same order in which you defined the table fields. For example, the fol-
lowing statements add a new row to the inventory table in the guitars database:
$SQLstringƒ=ƒ"INSERTƒINTOƒinventoryƒVALUES('Ovation',ƒ
ƒƒƒƒƒƒ'1777ƒLXƒLegend',ƒ1049.00,ƒ2)";
$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ƒrecord.</p>";
Also remember that you must specify NULL in any fields for which you do not have a 9
value. For example, if you do not know the quantity of guitars in stock for the Ovation
guitar, you can enter NULL as the last item in the VALUES list, as follows:
$SQLstringƒ=ƒ"INSERTƒINTOƒinventoryƒVALUES('Ovation',ƒ
ƒƒƒƒƒƒ'1777ƒLXƒLegend',ƒ1049.00,ƒNULL)";
To add multiple records to a database, you use the LOAD DATA statement and the
mysqli_query() function with a local text file containing the records you want to
add.The following statement loads a file named inventory.txt into the inventory table
in the guitars database:
$SQLstringƒ=ƒ"LOADƒDATAƒLOCALƒINFILEƒ'inventory.txt'ƒ
ƒƒƒƒƒINTOƒTABLEƒinventory";
To update records in a table, you use the UPDATE, SET, and WHERE keywords with the
mysqli_query() function. The UPDATE keyword specifies the name of the table to
update and the SET keyword specifies the value to assign to the fields in the records that
match the condition in the WHERE keyword. For example, the following statements
modify the price of the Fender DG7 guitar to $368.20:
$SQLstringƒ=ƒ"UPDATEƒinventoryƒSETƒprice=368.20ƒ
ƒƒƒƒƒWHERE make='Fender'ƒANDƒmodel='DG7'";
$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ƒmodifiedƒtheƒrecords.</p>";
454 Chapter 9 Manipulating MySQL Databases with PHP

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

3. Add the following statements above the mysqli_close() statement to


build a query string that will insert the values into the diver table:
$SQLstringƒ=ƒ"INSERTƒINTOƒdiversƒVALUES(NULL,ƒ'$First',ƒ'$Last',ƒ
'$Phone',ƒ'$Address',ƒ'$City',ƒ'$State',ƒ'$Zip')";

4. Add the following statements above the mysqli_close() statement to exe-


cute the query:
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring)
ƒƒƒƒƒƒƒOrƒdie("<p>Unableƒtoƒexecuteƒtheƒquery.</p>"
ƒƒƒƒƒƒƒƒƒƒƒƒƒ.ƒ"<p>Errorƒcodeƒ"ƒ.ƒmysqli_errno($DBConnect)
ƒƒƒƒƒƒƒƒƒƒƒƒƒ.ƒ":ƒ"ƒ.ƒmysqli_error($DBConnect))ƒ.ƒ"</p>";
5. Add the following mysqli_insert_id() statement above the
mysqli_close() statement to assign the new primary key to the
$DiverID variable:
$DiverIDƒ=ƒmysqli_insert_id($DBConnect);
6. Finally, add the following text and elements to the end of the document body.
The form allows users to register for classes by clicking the Register for
Classes button, which opens a script named CourseListings.php. Notice that
9
the form includes a hidden variable that is assigned the value of the
$DiverID variable.This ensures that the diver ID is passed to the
CourseListings.php script when the user clicks the Register for Classes button.
<p>Thanksƒ<?=ƒ$Firstƒ?>!ƒYourƒnewƒdiverƒIDƒisƒ<strong><?=ƒ
$DiverIDƒ?></strong>.</p>
<formƒaction="CourseListings.php"ƒmethod="get">
<p><inputƒtype="submit"ƒvalue="RegisterƒforƒClasses"ƒ/>
<inputƒtype="hidden"ƒname="diverID"ƒvalue="<?=ƒ$DiverIDƒ?>"ƒ
/></p>
</form>
7. Save the GetDiverID.php document and close it in your text editor.
8. Open the Registration.html file in your Web browser by entering the fol-
lowing URL: http://localhost/PHP_Projects/Chapter.09/Chapter/
Registration.html. Enter values into the New Diver Registration form and
click the Get Diver ID button.You should be assigned a new diver ID of 1.
You should see the Web page shown in Figure 9-12.
456 Chapter 9 Manipulating MySQL Databases with PHP

Figure 9-12 Register Diver Web page

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"ƒ/>

4. Add the following heading element to the document body:


<h1>AquaƒDon'sƒScubaƒSchool</h1>
<h2>ClassƒRegistrationƒForm</h2>
5. Add the following script section to the end of the document body:
<?php
?>
Manipulating Records 457

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>

11. Save the document as CourseListings.php in the Chapter directory for


Chapter 9, and then close it in your text editor.
12. Open the Registration.html file in your Web browser by entering the fol-
lowing URL: http://localhost/PHP_Projects/Chapter.09/
Chapter/Registration.html. Enter an existing diver ID into the Returning
Divers form and click the Class Registration button.You should see the
Web page shown in Figure 9-13.
Manipulating Records 459

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>

12. Save the document as RegisterDiver.php in the Chapter directory for


Chapter 9, and then close it in your text editor.
13. Return to the Course Listings page in your Web browser. Select a class, as
well as the days and times you want to take it, and then click the Register
button.You should see a message indicating that the registration table
was created successfully, along with a message confirming your registration in
the class, as shown in Figure 9-14.

Figure 9-14 Registration Confirmation Web page

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"ƒ/>

4. Add the following heading element to the document body:


<h1>AquaƒDon'sƒScubaƒSchool</h1>
<h2>Thisƒisƒyourƒcurrentƒschedule:</h2>
5. Add the following script section to the end of the document body:
<?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. 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.

Figure 9-15 Review Schedule Web page


464 Chapter 9 Manipulating MySQL Databases with PHP

Returning Information on Affected Records


As you have learned, the mysqli_num_rows() function returns the number of rows
in a query result and the mysqli_num_fields() function returns the number of
fields in a query result. In addition, PHP includes two functions, mysqli_
affected_rows() and mysqli_info(), which you can use to return information
on the records that were affected by a query. First, you learn how to use the
mysqli_affected_rows() function.

Using the mysqli_affected_rows() Function


With queries that return results, such as SELECT queries, you can use the
mysqli_num_rows() function to find the number of records returned from the query.
However, with queries that modify tables but do not return results, such as INSERT,
UPDATE, and DELETE queries, you can use the mysqli_affected_rows() function
to determine the number of affected rows.You pass to the mysqli_affected_rows()
function the variable containing the database connection returned from the
mysqli_connect() function—not the variable containing the result pointer from the
mysqli_query() function. For example, the following statements print the number
of rows affected by an UPDATE query. Figure 9-16 shows the output in a Web browser.
$SQLstringƒ=ƒ"UPDATEƒinventoryƒSETƒprice=368.20ƒ
ƒƒƒƒƒWHEREƒmake='Fender'ƒANDƒmodel='DG7'";
$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ƒupdatedƒ"ƒ
ƒƒƒƒƒ.ƒmysqli_affected_rows($DBConnect)ƒ.ƒ"ƒrecord(s).</p>";

Figure 9-16 Output of mysqli_affected_rows() function for an UPDATE query

The following code contains another example of the mysqli_affected_rows()


function, this time with a DELETE query:
Manipulating Records 465

$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>";

Using the mysqli_info() Function


For queries that add or update records, or that alter a table’s structure, you can use the
mysqli_info() function to return information about the query. The mysqli_
info() function returns the number of operations for various types of actions, depend-
ing on the type of query. For example, with INSERT queries, the mysqli_info()
function returns the number of records added and duplicated, along with the number
of warnings. However, for LOAD DATA queries, the mysqli_info() function returns
the number of records added, deleted, and skipped, along with the number of warnings.
As with the mysqli_affected_rows() function, you pass to the mysqli_info()
function the variable containing the database connection from the mysqli_connect()
function. The mysqli_info() function returns information about the last query that
9
was executed on the database connection. However, the mysqli_info() function
returns information about queries that match one of the following formats:
■ INSERT INTO...SELECT...
■ INSERT INTO...VALUES (...),(...),(...)
■ LOAD DATA INFILE ...
■ ALTER TABLE ...
■ UPDATE ...
For any queries that do not match one of the preceding formats, the mysqli_info()
function returns an empty string. Notice that the format for adding records with the
INSERT and VALUES keywords includes multiple value sets. The mysqli_info()
function only returns query information when you add multiple records with the
INSERT keyword. For example, the mysqli_info() function in the following exam-
ple returns an empty string because the INSERT query only adds a single record:
$SQLstringƒ=ƒ"INSERTƒINTOƒinventoryƒVALUES('Ovation',ƒ
ƒƒƒƒƒƒ'1777ƒLXƒLegend',ƒ1049.00,ƒ2)";
$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ƒrecord.</p>";
echoƒ"<p>"ƒ.ƒmysqli_info($DBConnect)ƒ.ƒ"</p>";
466 Chapter 9 Manipulating MySQL Databases with PHP

In comparison, the following statements print the query information shown in


Figure 9-17 because the INSERT query adds multiple records:
$SQLstringƒ=ƒ"INSERTƒINTOƒinventory
ƒƒƒƒƒVALUES('Ovation',ƒ'1777ƒLXƒLegend',ƒ1049.00,ƒ2),
ƒƒƒƒƒ('Ovation',ƒ'1861ƒStandardƒBalladeer',ƒ699.00,ƒ1),
ƒƒƒƒƒ('Ovation',ƒ'TangentƒSeriesƒT357',ƒ569.00,ƒ3)";
$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>";

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

Figure 9-18 Output of mysqli_info() function for a LOAD DATA query

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

❐ The mysqli_num_rows() function returns the number of rows in a query result,


and the mysqli_num_fields() function returns the number of fields in a
query result.
❐ The mysqli_free_result() function closes a resultset.
❐ You use the CREATE DATABASE statement with the mysqli_query() function
to create a new database.
❐ You use the DROP DATABASE statement with the mysqli_query() function to
delete a database.
❐ You use the CREATE TABLE statement with the mysqli_query() function to
create a table.
❐ You use the DROP TABLE statement with the mysqli_query() function to
delete a table.
❐ To identify a field as a primary key in MySQL, you include the PRIMARY KEY
keywords 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.
❐ You use the INSERT and VALUES keywords with the mysqli_query() function
to add records to a table.
❐ You use the LOAD DATA statement and the mysqli_query() function with a
local text file to add multiple records to a database.
❐ You use the UPDATE, SET, and WHERE keywords with the mysqli_query() func-
tion to update records in a table.
❐ You use the DELETE and WHERE keywords with the mysqli_query() function to
delete records in a table.
❐ With queries that return results, such as SELECT queries, you can use the mysqli_
num_rows() function to find the number of records returned from the query.
❐ The mysqli_info() function returns the number of operations for various types
of actions, depending on the type of query.

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

3. To which of the following functions do you need to pass a variable representing


the database connection? (Choose all that apply.)
a. mysqli_get_client_info()
b. mysqli_get_host_info()
c. mysqli_get_proto_info()
d. mysqli_get_server_info()
4. What is the correct syntax for selecting a database with the
mysqli_select_db() function?
a. mysqli_select_db(connection)
b. mysqli_select_db(database)
c. mysqli_select_db(connection, database)
d. database = mysqli_select_db(connection)
5. Explain the types of errors that can occur when accessing MySQL databases and
other types of data sources with PHP.
6. The following code structure prevents error messages from printing in the event 9
that the database connection is not available. True or False?
$DBConnectƒ=ƒmysqli_connect("localhost",ƒ"dongosselin",ƒ
ƒƒƒƒƒ"rosebud",ƒ"flightlog");
ifƒ(!$DBConnect)
ƒƒƒƒƒƒechoƒ"<p>Theƒdatabaseƒserverƒisƒnotƒavailable.</p>";
elseƒƒ{
ƒƒƒƒƒechoƒ"<p>Successfullyƒconnectedƒtoƒtheƒdatabaseƒserver.</p>";
ƒƒƒƒƒmysqli_close($DBConnect);
}
7. Explain the concept of bulletproofing your code.
8. Which of the following characters suppresses error messages in PHP?
a. *
b. &
c. #
d. @
9. Which of the following functions terminate script execution? (Choose all that
apply.)
a. exit()
b. bye()
c. die()
d. quit()
470 Chapter 9 Manipulating MySQL Databases with PHP

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

18. Which of the following SQL keywords creates an autoincrementing field?


a. AUTO
b. INCREMENT
c. AUTO_INCREMENT
d. AUTOINCREMENT
19. Which of the following functions returns the number of rows affected by queries
that do not return results, such as INSERT, UPDATE, and DELETE queries?
a. mysqli_affected_rows()
b. mysqli_rows()
c. mysqli_get_changed()
d. mysqli_fetch_rows()
20. The function returns the number of operations for various
types of actions, depending on the type of query.
a. mysqli_get_info()
b. mysqli_operations() 9
c. mysqli_info()
d. mysqli_fetch_actions()

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

9. Open HitCounter.php file in your Web browser by entering the following


URL: http://localhost/PHP_Projects/Chapter.09/Projects/
HitCounter.php. The first time you open the Web page, you should see the mes-
sage about being the first visitor to the Web site, along with a hit count of 1.
Reload the Web page a few times to see if the count increases.
10. Close your Web browser window.

Hands-On Project 9-2


In this project, you create a Web page that allows visitors to your site to sign a guest book
that is saved to a database.
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 “Guest Book” as the content of the <title> element.
2. Add the following text and elements to the document body:
<h2>Enterƒyourƒnameƒtoƒsignƒourƒguestƒbook</h2>
<formƒmethod="get"ƒaction="SignGuestBook.php">
<p>FirstƒNameƒ<inputƒtype="text"ƒname="first_name"ƒ/></p> 9
<p>LastƒNameƒ<inputƒtype="text"ƒname="last_name"ƒ/></p>
<p><inputƒtype="submit"ƒvalue="Submit"ƒ/></p>
</form>
3. Save the document as GuestBook.html in the Projects directory for Chapter 9.
4. 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 “Guest Book” as the content of the <title> element.
5. Add the following script section to the document body:
<?php
?>
6. Add the following statements to the script section to ensure that visitors enter
their first and last names:
ifƒ(empty($_GET['first_name'])ƒ||ƒempty($_GET['last_name']))
ƒƒƒƒƒdie("<p>Youƒmustƒenterƒyourƒfirstƒandƒlastƒname!ƒClickƒyourƒ
browser'sƒBackƒbuttonƒtoƒreturnƒtoƒtheƒGuestƒBookƒform.</p>");
7. 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>";
474 Chapter 9 Manipulating MySQL Databases with PHP

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

11. Save the document as SignGuestBook.php in the Projects directory for


Chapter 9.
12. Open GuestBook.html file in your Web browser by entering the following
URL:
http://localhost/PHP_Projects/Chapter.09/Projects/GuestBook.html.
Test the form to see if you can add your name to the database.
13. Close your Web browser window.

Hands-On Project 9-3


In this project, add a document to the Guest Book program you created in Hands-On
Project 9-2. This document displays the entries in the guest book.
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 “Guest Book” as the content of the <title> element.
2. Add the following script section to the document body:
<?php
?>
9
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>";
4. Add the following statements to the end of the script section to connect to the
guestbook database. If the database does not exist, a message prints that the
guest book does not contain any entries.
$DBNameƒ=ƒ"guestbook";
ifƒ(!@mysqli_select_db($DBConnect,ƒ$DBName))
ƒƒƒƒƒdie("<p>Thereƒareƒnoƒentriesƒinƒtheƒguestƒbook!</p>");
5. Add the following statements to the end of the script section to select all the
records in the visitors table. If no records are returned, a message prints that
the guest book does not contain any entries.
$TableNameƒ=ƒ"visitors";
$SQLstringƒ=ƒ"SELECTƒ*ƒFROMƒ$TableName";
$QueryResultƒ=ƒ@mysqli_query($DBConnect,ƒ$SQLstring);
ifƒ(mysqli_num_rows($QueryResult)ƒ==ƒ0)
ƒƒƒƒƒdie("<p>Thereƒareƒnoƒentriesƒinƒtheƒguestƒbook!</p>");
476 Chapter 9 Manipulating MySQL Databases with PHP

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.

Case Project 9-1


Create a document with a form that registers users for a professional conference.
Case Projects 477

Case Project 9-2


Create a telephone directory application that saves entries to a single text file.You should
include standard telephone directory fields in the database, such as first name, last name,
address, city, state, zip, telephone number, and so on. Create a document as a main “direc-
tory,” where you can select and retrieve records. Also, create one document that you can
use to add new entries to the database and another document that you can use to edit
entries.

Case Project 9-3


Create a Web page to be used for storing software development bug reports in a MySQL
database. Include fields such as product name and version, type of hardware, operating
system, frequency of occurrence, and proposed solutions. Include links on the main page
that allow you to create a new bug report and update an existing bug report.

Case Project 9-4


Create a Web site for tracking, documenting, and managing the process of interviewing
candidates for professional positions. On the main page, include a form with fields for
9
the interviewer’s name, position, and date of interview. Also include fields for entering
the candidate’s name, communication abilities, professional appearance, computer skills,
business knowledge, and interviewer’s comments. Clicking the Submit button should
save the data in a MySQL database. Include a link for opening a document that displays
each candidate’s interview information.

Case Project 9-5


Create a Web page that stores airline surveys in a MySQL database. Include fields for the
date and time of the flight, flight number, and so on. Also, include groups of radio but-
tons that allow the user to rate the airline on the following criteria:
❐ Friendliness of customer staff
❐ Space for luggage storage
❐ Comfort of seating
❐ Cleanliness of aircraft
❐ Noise level of aircraft
The radio buttons for each question should consist of the following options: No
Opinion, Poor, Fair, Good, or Excellent. Separate text files should store the results of a
single survey. Include a View Past Survey Results button on the main survey page that
displays a list of past survey results.

You might also like