
- •Initializing with Constructor Functions . . . . .
- •Into a Web page as a separate section. Although JavaScript code can
- •Is that standard php script delimiters are guaranteed to be available
- •In the block. Any text or lines between the opening /* characters and
- •2.7541 Are not integers; they are floating-point numbers. A floating-
- •Value 300
- •Is a value of 2.5, because 6 goes into 15 exactly 2.5 times. But if you
- •IsEven.Php.
- •Ing example,
- •Ing curly brace is on its own line following the function statements.
- •In php 3 and earlier, it was necessary to put a function definition
- •Is called an iteration. When the conditional expression evaluates
- •Including Files
- •13. Close your Web browser window.
- •Including Files
- •In php, you can also use two operators to combine strings. The first
- •Xhtml source code gen-
- •Input. Php provides several functions for manipulating the case of a
- •Is uppercase. If you need the reverse of ucfirst(), the lcfirst()
- •In some situations, you will need to find and extract characters and
- •Information Interchange, or ascii, which are numeric represen-
- •In comparison, the following preg_match() function returns a value
- •In the pattern is optional. The following code demonstrates how to
- •Values; any strings you validate against a regular expression must
- •Value of 1 because the top-level domain contains a valid value of .Com.
- •Is submitted using the “post” method, the form data is embedded in
- •Validating String Data
- •Xhtml tags or character entities. The message field is a text string
- •Value of the header element. For example:
- •Xhtml code within a php script section.
- •Is typically the person who created the resource. Otherwise, the net-
- •If even a single character of the Web page is sent prior to sending
- •Variables to the file_put_contents() function.
- •Xhtml hyperlink. To download a file from outside the xhtml
- •If...Else statement to display the appropriate version of the mes-
- •Iterating Through an Array
- •Iterating Through an Array
- •In Chapter 2, you learned how to use a foreach statement to iterate
- •Iterating Through an Array
- •Iterating Through an Array
- •In comparison, the following code declares and initializes
- •If ((!file_exists("MessageBoard/messages.Txt"))
- •Values from the array to create a thumbnail gallery of images in which
- •Introduction to Databases
- •Including php, allow you to create Web pages that can read and write
- •Introduction to Databases
- •Information that can be organized into ordered sets of data, and
- •Information. Each recipe in a recipe database, for instance, is a single
- •Introduction to Databases
- •Index, which identifies records in a database to make retrievals and
- •In a single table. However, you might want to break the information
- •Into multiple tables to better organize it into logical sets. Another
- •Information in one of the tables confidential and accessible only by
- •Is the employee information table from Figure 7-1. The related table
- •Is a payroll table that contains confidential salary and compensation
- •Information. Notice that each table contains an identical number of
- •Introduction to Databases
- •Introduction to Databases
- •In a junction
- •Introduction to Databases
- •In a relational format is called a relational database management
- •Is a standard data manipulation language among many dbmSs.
- •Into the query area at the top of the screen or by dragging tables and
- •It is important to understand that even though many dbmSs sup-
- •Introduction to Databases
- •If you ever
- •Is. In comparison, the bigint data type stores integer values between
- •5 Rows in set (0.00 sec)
- •Int);[enter ]
- •Important, these two tabs can cause you to lose all of the data in the
- •Internet Explorer to export the table, click the Save button in the File
- •Ifies the table being changed and the change to make.
- •It easier for you to write php code that can be used with a variety of
- •Information about queries that match one of the following formats:
- •Various types of actions, depending on the type of query.
- •Include fields for the date and time of the flight, flight number, and
- •In the ChineseZodiac folder and upload the file to the server. Open
- •Including white space,
- •Information on a Web server. When you start a new session, the
- •Introduction to Object-Oriented Programming
- •Introduction to Object-Oriented
- •Variables associated with an object are called properties or attributes.
- •In the Loan object example, a function that calculates the number of
- •Introduction to Object-Oriented Programming
- •Introduction to Object-Oriented Programming
- •Include instances of objects inherit the object’s functionality.
- •In this chapter, you will create the Web site for an online order form
- •In an online store application. The application includes information
- •Ity of building a working online store. Online store classes are very
- •Information and products. The OnlineStore class requires that store
- •Information is stored in a table containing six fields: storeId, name,
- •Information. Instead, the class simply uses session iDs to keep track
- •Variable and function as necessary, without bothering with all this
- •In a class
- •Is developed. Imagine what would happen if Microsoft distributed
- •Ing class is invalid because it does not include an access specifier:
- •If they will not be supported by future xhtml versions or are not
- •Xhtml standards. To review the guide of current w3c css specifi-
- •Information to remind yourself or others of what the code is doing. A
- •Xhtml document to the external style sheet. This link informa-
- •If you select Apache from the WampServer menu and select Service
- •Ing code uses the number_format() function to add comma separa-
- •In data that a user submits to a php script.
- •Value of “On” and the display_startup_errors directive is assigned
- •Instead. By looking at the source code, you could see that the value of
- •Ing engine can even help locate logic errors.
- •In Chapter 8, along with the equivalent mssql_* functions, where
- •Inline styles, 632
- •Xhtml, 620–635 (continued)
For queries that add or update records, or that alter a table’s structure,
you can use the mysql_info() function to return information about the
query. This function returns the number of operations for various types
of actions, depending on the type of query. For example, with INSERT
queries, the mysql_info() function returns the number of records
added and duplicated, along with the number of warnings. However,
for LOAD DATA queries, the mysql_info() function returns the num-
ber of records added, deleted, and skipped, along with the number of
warnings. As with the mysql_affected_rows() function, you pass
to the mysql_info() function the variable that contains the database
connection from the mysql_connect() function. The mysql_info()
function returns information about the last query that was executed on
the database connection. However, the mysql_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
mysql_info() function returns an empty string. Notice that the format
for adding records with the INSERT and VALUES keywords includes mul-
tiple value sets. The mysql_info() function only returns query infor-
mation when you add multiple records with the INSERT keyword. For
example, the mysql_info() function in the following example returns
an empty string because the INSERT query only adds a single record:
$SQLstring = "INSERT INTO company_cars " .
" (license, model_year, make, model, mileage) " .
" VALUES('CPQ-893', 2011, 'Honda', 'Insight', " .
" 49.2)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}
471

CHAPTER
8
Manipulating
MySQL Databases with PHP
In
comparison, the following statements display the query informa-
tion
shown in Figure 8-6 because the INSERT
query
adds multiple
records:
$SQLstring
= "INSERT INTO company_cars " .
"
(license, model_year, make, model, mileage) " .
" VALUES " .
" ('CPQ-894', 2011, 'Honda', 'Insight', 49.2), " .
" ('CPQ-895', 2011, 'Honda', 'Insight', 17.9), " .
" ('CPQ-896', 2011, 'Honda', 'Insight', 22.6)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}
472
Figure 8-6 Output of the mysql_info() function for an INSERT query
that adds multiple records
The mysql_info() function also returns information for LOAD DATA
queries. The following statements display the output shown in
Figure 8-7:
$SQLstring = "LOAD DATA INFILE 'company_cars.txt'
INTO TABLE company_cars;";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}

Retrieving
Records
473
Figure
8-7
Output
of the mysql_info()
function
for a LOAD
DATA query
Short
Quiz
1.
What
statement is used to add multiple records to a database
from
an external file?
Explain
the purpose of the three keywords in the following
SQL
query:
$SQLstring
= "UPDATE company_cars SET mileage=50112.3
WHERE
license='AK-1234'";
2.
3.
What records would be deleted from the company_cars table
using the following query?
$SQLstring = "DELETE FROM company_cars";
4.
What argument is passed to the mysql_affected_rows()
function to determine the number of rows affected by a
query?
Retrieving Records
In this section, you will learn how to use PHP to retrieve records
from tables in a database.
Working with Query Results
Recall that for SQL statements that return results, such as SELECT and
SHOW statements, the mysql_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

CHAPTER
8
Manipulating
MySQL Databases with PHP
the
database records through the result pointer, you must use one of
the
functions listed in Table 8-2.
Function
mysql_data_seek($Result,
position)
Description
Moves
the result pointer to a specified row in the
resultset
Returns
the fields in the current row of a resultset
into
an indexed array, associative array, or both,
and
moves the result pointer to the next row
Returns
the fields in the current row of a resultset
into
an associative array and moves the result
pointer
to the next row
Returns
the field lengths for the current row in a
resultset
into an indexed array
Returns
the fields in the current row of a resultset
into
an indexed array and moves the result pointer
to
the next row
474
mysql_fetch_array($Result,
MYSQL_ASSOC
| MYSQL_NUM |
MYSQL_BOTH)
mysql_fetch_assoc($Result)
mysql_fetch_lengths($Result)
mysql_fetch_row($Result)
Table
8-2
Common
PHP functions for accessing database results
First,
you will learn how to use the mysql_fetch_row()
function
to
retrieve
fields into an indexed array.
Retrieving
Records into an Indexed Array
In
Chapter 5, 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 mysql_fetch_row()
function
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 displays the contents of the fields in the first row of the
company_cars
table
in the vehicle_fleet
database:
$SQLstring
= "SELECT * FROM company_cars";
$QueryResult
= @mysql_query($SQLstring, $DBConnect);
if
($QueryResult === FALSE)
echo
"<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
$Row = mysql_fetch_row($QueryResult);
echo "<p><strong>License</strong>: {$Row[0]}<br />";
echo "<strong>Make</strong>: {$Row[1]}<br />";
echo "<strong>Model</strong>: {$Row[2]}<br />";
echo "<strong>Mileage</strong>: {$Row[3]}<br />";
echo "<strong>Year</strong>: {$Row[4]}</p>";
}

Retrieving
Records
The
mysql_fetch_row()
function
in the preceding example 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 complete
example
that uses a while
statement
to display all of the rows in the
company_cars
table
to an HTML table. Figure 8-8 shows how the
table
appears in a Web browser.
$SQLstring
= "SELECT * FROM company_cars";
$QueryResult
= @mysql_query($SQLstring, $DBConnect);
echo
"<table width='100%' border='1'>\n";
echo
"<tr><th>License</th><th>Make</th><th>Model</th>
<th>Mileage</th><th>Year</th></tr>\n";
while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>\n";
}
echo "</table>\n";
475
Figure 8-8
Output of the company_cars table in a Web browser
To create a script that selects and displays all of the records in the
subscribers table:
1.
Create a new document in your text editor.
CHAPTER
8
Manipulating
MySQL Databases with PHP
2.
Type
the <!DOCTYPE>
declaration,
<html>
element,
header
information,
and <body>
element.
Use the strict DTD and
“Newsletter
Subscribers” as the content of the
Add the following header and script section to the end of the
document body:
<h1>Newsletter Subscribers</h1>
<?php
?>
3.
476
4.
Add the following include() statement to the script section:
include("inc_db_newsletter.php");
5.
After the include() statement, add the following statements to
handle a successful selection of the newsletter database:
if ($DBConnect !== FALSE) {
mysql_close($DBConnect);
}
6.
Add the following variable declarations and mysql_query()
statement immediately before the mysql_close() function. The
mysql_query() statement selects all existing records from the
subscribers table.
$TableName = "subscribers";
$SQLstring = "SELECT * FROM $TableName";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
7.
Add the following statements immediately before the
mysql_close() function. These statements use the
mysql_fetch_row() function to display the results in a table:
echo "<table width='100%' border='1'>\n";
echo "<tr><th>Subscriber ID</th>" .
"<th>Name</th><th>Email</th>" .
"<th>Subscribe Date</th>" .
"<th>Confirm Date</th></tr>\n";
while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) {
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></tr>\n";
};
echo "</table>\n";
8.
Save the file as ShowNewsletterSubscribers.php in the
Chapter directory for Chapter 8, and then upload the document
to the Web server.

Retrieving
Records
9.
Open
ShowNewsletterSubscribers.php in your Web browser by
entering
the following URL: http://<yourserver>/PHP_Projects/
Chapter.08/Chapter/ShowNewsletterSubscribers.php.
Your Web
page
should look like Figure 8-9, although you may have added
or
deleted more entries.
10.
Close
your Web browser window.
477
Figure
8-9
Output
of the ShowNewsletterSubscribers.php script
Retrieving
Records into an Associative Array
The
mysql_fetch_assoc()
function
returns the fields in the cur-
rent
row of a resultset into an associative array and moves the
result
pointer to the next row. The primary difference between the
mysql_fetch_assoc()
function
and the mysql_fetch_row()
func-
tion
is that instead of returning the fields into an indexed array, the
mysql_fetch_assoc()
function
returns the fields into an associative
array
and uses each field name as the array key. For example, the fol-
lowing
code uses the mysql_fetch_assoc()
function
to display the
contents
of the fields in the first row in the company_cars
table
of the
vehicle_fleet
database.
Notice that the echo
statements
refer to keys
instead
of indexes in the $Row[]
array.
$Row
echo
echo
echo
echo
echo
=
mysql_fetch_assoc($QueryResult);
"<p><strong>License</strong>:
{$Row['license']}<br />";
"<strong>Make</strong>:
{$Row['make']}<br />";
"<strong>Model</strong>:
{$Row['model']}<br />";
"<strong>Mileage</strong>:
{$Row['mileage']}<br />";
"<strong>Year</strong>:
{$Row['year']}</p>";
CHAPTER
8
Manipulating
MySQL Databases with PHP
The
following code shows an associative array version of the while
statement
that displays all of the rows in the company_cars
table
to an
HTML
table:
$SQLstring
= "SELECT * FROM company_cars";
$QueryResult
= @mysql_query($SQLstring, $DBConnect);
echo
"<table width='100%' border='1'>\n";
echo
"<tr><th>License</th><th>Make</th><th>Model</th>
<th>Mileage</th><th>Year</th></tr>\n";
while (($Row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
echo "<tr><td>{$Row['license']}</td>";
echo "<td>{$Row['make']}</td>";
echo "<td>{$Row['model']}</td>";
echo "<td align='right'>{$Row['mileage']}</td>";
echo "<td>{$Row['year']}</td></tr>\n";
}
echo "</table>\n";
478
To change the query statement in ShowNewsletterSubscribers.php
that selects all the records in the subscribers table so that it uses an
associative array:
1.
Return to the ShowNewsletterSubscribers.php document in
your text editor.
Replace the mysql_fetch_row() function with a
mysql_fetch_assoc() function.
Modify the echo statements in the while statement so they ref-
erence the keys in the associative array instead of the index val-
ues. Your modified code should appear as follows:
while (($Row = mysql_fetch_assoc($QueryResult))
!== FALSE) {
echo "<tr><td>{$Row['subscriberID']}</td>";
echo "<td>{$Row['name']}</td>";
echo "<td>{$Row['email']}</td>";
echo "<td>{$Row['subscribe_date']}</td>";
echo "<td>{$Row['confirmed_date']}</td></tr>\n";
};
2.
3.
4.
Save the ShowNewsletterSubscribers.php file and upload it
to the server.
Open ShowNewsletterSubscribers.php in your Web browser by
entering the following URL: http://<yourserver>/PHP_Projects/
Chapter.08/Chapter/ShowNewsletterSubscribers.php. Your Web
page should look the same as it did before you modified the code
to use the mysql_fetch_assoc() function.
Close your Web browser window.
5.
6.

Retrieving
Records
Closing
Query Results
When
you are finished working with query results retrieved with the
mysql_query()
function,
you should use the mysql_free_result()
function
to close the resultset. This ensures that the resultset doesn’t
keep
taking up space in your Web server’s memory. (As you’ll recall,
you
need to close a database connection for the same reason.) If you
do
not call mysql_free_result(),
the memory used by the resultset
will
be freed when the script completes. To close the resultset, pass
to
the mysql_free_result()
function
the variable containing the
result
pointer from the mysql_query()
function.
The following code
uses
the mysql_free_result()
function
to close the $QueryResult
variable:
$SQLstring
= "SELECT * FROM company_cars";
$QueryResult
= @mysql_query($SQLstring, $DBConnect);
if
($QueryResult === FALSE)
echo
"<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else
echo "<p>Successfully executed the query.</p>";
...
mysql_free_result($QueryResult);
mysql_close($DBConnect);
You can only
use the
mysql_
free_
result()
function with SQL state-
ments that return results,
such as SELECT queries,
and only when the SQL
statement successfully
returned results. If you
attempt to use the
mysql_free_result()
function with SQL state-
ments that do not return
results, such as the
CREATE DATABASE and
CREATE TABLE state-
ments, or on an empty
resultset, you will receive
an error.
479
To add a mysql_free_result() function to the
ShowNewsletterSubscribers.php script:
1.
Return to the ShowNewsletterSubscribers.php document in
your text editor.
Add the following statement above the mysql_close()
statement:
mysql_free_result($QueryResult);
2.
3.
Save the ShowNewsletterSubscribers.php file and upload it to
the Web server. Then open the script in your Web browser by
entering the following URL: http://<yourserver>/PHP_Projects/
Chapter.08/Chapter/ShowNewsletterSubscribers.php. Your
Web page should look the same as it did before you added the
mysql_free_result() function.
Close your Web browser window.
4.
Accessing Query Result Information
As you have learned, the functions mysql_affected_rows()
and mysql_info() return information on the records that were
affected by a query. You also learned that the mysql_num_rows()

CHAPTER
8
Manipulating
MySQL Databases with PHP
function
returns the number of rows in a query result. You use
the
mysql_num_fields()
function
to return the number of fields
in
a query result. As with the mysql_num_rows()
function,
the
mysql_num_fields()
function
accepts a database connection variable
as
an optional argument.
480
The
following code demonstrates how to use both functions with
the
query results returned from the vehicle_fleet
database.
If the
number
of rows and fields in the query result are not equal to zero, an
echo
statement
displays the number of rows and fields. However, if
the
number of rows and fields in the query result are equal to zero, an
echo
statement
displays “Your query returned no results.” Figure 8-10
shows
the output if the company_cars
table
in the vehicle_fleet
database
contains 11 rows and 5 fields.
$SQLstring
= "SELECT * FROM company_cars";
$QueryResult
= @mysql_query($SQLstring, $DBConnect);
if
($QueryResult === FALSE)
echo
"<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else
echo "<p>Successfully executed the query.</p>";
$NumRows = mysql_num_rows($QueryResult);
$NumFields = mysql_num_fields($QueryResult);
if ($NumRows != 0 && $NumFields != 0)
echo "<p>Your query returned " .
mysql_num_rows($QueryResult) . " rows and "
. mysql_num_fields($QueryResult) . " fields.</p>";
else
echo "<p>Your query returned no results.</p>";
mysql_close($DBConnect);
Figure 8-10
Output of the number of rows and fields returned from a query

Retrieving
Records
To
add statements to the ShowNewsletterSubscribers.php script that
display
the number of returned rows and fields:
1.
Return
to the ShowNewsletterSubscribers.php
document
in
your
text editor.
Add
the following statements above the
mysql_close($DBConnect);
statement:
$NumRows
= mysql_num_rows($QueryResult);
$NumFields
= mysql_num_fields($QueryResult);
echo
"<p>Your query returned the above "
.
mysql_num_rows($QueryResult)
. " rows and ". mysql_num_fields($QueryResult)
. " fields:</p>";
2.
481
3.
Save the ShowNewsletterSubscribers.php file, upload it to the
Web server, and open it in your Web browser by entering the
following URL: http://<yourserver>/PHP_Projects/Chapter.08/
Chapter/ShowNewsletterSubscribers.php. Your Web page should
look like Figure 8-11.
Close your Web browser window.
4.
Figure 8-11
The Newsletter Subscribers table with row and field counts

CHAPTER
8
Manipulating
MySQL Databases with PHP
Short
Quiz
1.
482
What
two functions return the fields in the current row of a
resultset
into an indexed array and move the pointer to the
next
row?
Describe
the differences between the mysql_fetch_row()
function
and the mysql_fetch_assoc()
function.
Contrast
the mysql_num_rows()
function
and the
mysql_num_fields()
function.
What
function is used to close the query resultset when you
are
finished working with the results?
Explain
why the mysql_free_result()
function
does
not
work with the CREATE
DATABASE and
CREATE
TABLE
statements.
2.
3.
4.
5.
Summing
Up
•
The
database server.
• The
mysql_close() function closes a database connection.• The
mysql_errno() function returns the error code from the lastattempted MySQL function call or zero if no error occurred.
• The
mysql_error() function returns the error message from thelast attempted MySQL function call or returns an empty string if
no error occurred.
• The
die() and exit() functions terminate script execution.• The error control operator (
@) suppresses error messages.• You use the
mysql_create_db() function to create a new database.• The
mysql_select_db() function selects a database.• You use the
mysql_drop_db() function to delete a database.• The
mysql_query() function sends SQL statements to MySQL.
Comprehension
Check
•
A
result pointer is a special type of variable that refers to the
currently selected row in a resultset.
• You use the
CREATE TABLE statement with the mysql_query()function to create a table.
• The
PRIMARY KEY clause indicates a field or fields that will be usedas a referential index for the table.
• The
AUTO_INCREMENT clause creates a field that is automaticallyupdated with the next sequential value for that column.
• The
NOT NULL clause creates a field that must contain data.• You use the
DROP TABLE statement with the mysql_query()function to delete a table.
• You use the
LOAD DATA statement and the mysql_query() functionwith a local text file to add multiple records to a database.
• You use the
UPDATE statement with the mysql_query() function toupdate records in a table.
• You use the
DELETE statement with the mysql_query() function todelete records from a table.
• The
mysql_info() function returns the number of operations for