Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

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

<title> element.

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

mysql_connect() function opens a connection to a MySQL

database server.

• The

mysql_close() function closes a database connection.

• The

mysql_errno() function returns the error code from the last

attempted MySQL function call or zero if no error occurred.

• The

mysql_error() function returns the error message from the

last 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 used

as a referential index for the table.

• The

AUTO_INCREMENT clause creates a field that is automatically

updated 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() function

with a local text file to add multiple records to a database.

• You use the

UPDATE statement with the mysql_query() function to

update records in a table.

• You use the

DELETE statement with the mysql_query() function to

delete records from a table.

• The

mysql_info() function returns the number of operations for
Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]