Specifications

Its useful to know thisif we plan to process or display the results, we know how many there
are and can now loop through them:
for ($i=0; $i <$num_results; $i++)
{
// process results
}
In each iteration of this loop, we are calling mysql_fetch_array(). The loop will not execute
if no rows are returned. This is a function that takes each row from the resultset and returns the
row as an associative array, with each key an attribute name and each value the corresponding
value in the array:
$row = mysql_fetch_array($result);
Given the associative array $row, we can go through each field and display them appropriately,
for example:
echo “<br>ISBN: “;
echo stripslashes($row[“isbn”]);
As previously mentioned, we have called stripslashes() to tidy up the value before display-
ing it.
There are several variations on getting results from a result identifier. Instead of an associative
array, we can retrieve the results in an enumerated array with mysql_fetch_row(), as follows:
$row = mysql_fetch_row($result);
The attribute values will be listed in each of the array values $row[0], $row[1], and so on.
You could also fetch a row into an object with the mysql_fetch_object() function:
$row = mysql_fetch_object($result);
You can then access each of the attributes via $row->title, $row->author, and so on.
Each of these approaches fetches a row at a time. The other approach is to access a field at a
time using mysql_result(). For this, you must specify the row number (from zero to the num-
ber of rows1) as well as the field name. For example
$row = mysql_result($result, $i, “title”);
You can specify the field name as a string (either in the form “title” or “books.title”) or as
a number (as in mysql_fetch_row()). You shouldnt mix use of mysql_result() with any of
the other fetching functions.
The row-oriented fetch functions are far more efficient than mysql_result(), so in general
you should use one of those.
Accessing Your MySQL Database from the Web with PHP
C
HAPTER 10
10
ACCESSING
YOUR MYSQL
DATABASE
237
13 7842 CH10 3/6/01 3:36 PM Page 237