[ Team LiB ] Previous Section Next Section

Accessing Information

Now that we can add information to a database, we need to look at strategies for retrieving the information it contains. As you might guess, you can use mysql_query() to make a SELECT query. How do you use this to look at the returned rows, though? When you perform a successful SELECT query, mysql_query() returns a result resource. You can pass this resource to other functions to access and gain information about a resultset.

Finding the Number of Rows Found by a Query

You can find the number of rows returned as a result of a SELECT query using the mysql_num_rows() function. mysql_num_rows() requires a result resource and returns a count of the rows in the set. Listing 13.4 uses a SQL SELECT statement to request all rows in the domains table that have a sex field containing F and then uses mysql_num_rows() to determine the result set's size. If we only needed this figure, we could use MySQL's COUNT function. mysql_num_rows() is useful when you want to work with a found set and need some summary information before you begin.

Listing 13.4 Finding the Number of Rows Returned by a SELECT Statement with mysql_num_rows()
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 13.4 Using mysql_num_rows()</title>
 7: </head>
 8: <body>
 9: <?php
10: $user = "p24_user";
11: $pass = "cwaffie";
12: $db = "p24";
13: $link = mysql_connect( "localhost", $user, $pass );
14: if ( ! $link ) {
15:   die( "Couldn't connect to MySQL: ".mysql_error() );
16: }
17:
18: mysql_select_db( $db, $link )
19:   or die ( "Couldn't open $db: ".mysql_error() );
20:
21: $result = mysql_query( "SELECT * FROM domains where sex='F'" );
22: $num_rows = mysql_num_rows( $result );
23:
24: print "<p>$num_rows women have added data to the table</p>\n";
25:
26: // summarise data
27:
28: mysql_close( $link );
29: ?>
30: </body>
31: </html>

The mysql_query() function returns a result resource. We then pass this to mysql_num_rows(), which returns the total number of rows found.

We connect to the database on line 13 and select the database on line 18. On line 21 we call mysql_query(), passing it our SQL query. The function returns a result resource that we can then use with mysql_num_rows() on line 22. Having output summary information on line 24, we are ready to begin some more substantial work with our results. We do this in the next section.

Accessing a Resultset

After you have performed a SELECT query and gained a result resource, you can use a loop to access each found row in turn. PHP maintains an internal pointer that keeps a record of your position within a found set. This moves on to the next row as each one is accessed.

You can easily get an array of the fields in each found row with mysql_fetch_row(). This function requires a result resource, returning an array containing each field in the row. When the end of the found set is reached, mysql_fetch_row() returns false. Listing 13.5 outputs selected rows from the domains table to the browser.

Listing 13.5 Listing All Rows and Fields in a Table
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 13.5 Selecting Data</title>
 7: </head>
 8: <body>
 9: <?php
10: $user = "p24_user";
11: $pass = "cwaffie";
12: $db = "p24";
13: $link = mysql_connect( "localhost", $user, $pass );
14: if ( ! $link ) {
15:   die( "Couldn't connect to MySQL: ".mysql_error() );
16: }
17:
18: mysql_select_db( $db, $link )
19:   or die ( "Couldn't open $db: ".mysql_error() );
20:
21: $result = mysql_query( "SELECT * FROM domains where sex='F'" );
22: $num_rows = mysql_num_rows( $result );
23:
24: print "<p>$num_rows women have added data to the table</p>\n";
25:
26: print "<table border=\"1\">\n";
27: while ( $a_row = mysql_fetch_row( $result ) ) {
28:   print "<tr>\n";
29:   foreach ( $a_row as $field ) {
30:     print "\t<td>".stripslashes($field)."</td>\n";
31:   }
32:   print "</tr>\n";
33: }
34: print "</table>\n";
35: mysql_close( $link );
36: ?>
37: </body>
38: </html>

After we have connected to the server and selected the database, we use mysql_query() on line 21 to send a SELECT statement to the database server. We store the returned result resource in a variable called $result and use this to acquire the number of found rows as before.

In the test expression of our while statement on line 27, we assign the result of mysql_fetch_row() to the variable $a_row. Remember that an assignment operator returns the value of its right-hand operand, so the assignment resolves to true as long as mysql_fetch_row() returns a positive value. Within the body of the while statement, we loop through the row array contained in $a_row on line 29, outputting each element to the browser embedded in a table cell.

You can also access fields by name in one of two ways. mysql_fetch_array() returns a numeric array, as does mysql_fetch_row(). It also returns an associative array, with the names of the fields as the keys. The following fragment rewrites the while statement from Listing 13.5, incorporating mysql_fetch_array() (this replaces lines 26–34):


print "<table border=\"1\">\n";
while ( $a_row = mysql_fetch_array( $result ) ) {
  print "<tr>\n";
  print "<td>".stripslashes($a_row['mail'])."</td>";
  print "<td>".stripslashes($a_row['domain'])."</td>";
  print "</tr>\n";
}
print "</table>\n";

The default behavior of mysql_fetch_array() is to return an array indexed by a string that also contains the same values indexed numerically. This is fine if you want to refer to your fields individually. If, however, you need to dump all the array values and keys, you will not want this duplication. mysql_fetch_array() accepts an optional second argument, and this integer should be one of three built-in constants—MYSQL_ASSOC, MYSQL_NUM, or MYSQL_BOTH. Passing MYSQL_BOTH is redundant in that it enforces the default behavior. Passing MYSQL_ASSOC to mysql_fetch_array() ensures that the return array is indexed by strings only, and passing MYSQL_NUM to mysql_fetch_array() ensures that the return array is numerically indexed.

If you are seeking the functionality provided by


mysql_fetch_array( $result, MYSQL_ASSOC );

you can use a shortcut function introduced with PHP 4.03. mysql_fetch_assoc() is functionally identical to a call to mysql_fetch_array() with MYSQL_ASSOC.

You can also extract the fields from a row as properties of an object with mysql_fetch_object(). The field names become the names of the properties. The following fragment rewrites the while statement from Listing 13.5, this time incorporating mysql_fetch_object() (this replaces lines 26–34):


print "<table border=\"1\">\n";
while ( $a_row = mysql_fetch_object( $result ) ) {
  print "<tr>\n";
  print "<td>".stripslashes($a_row->mail)."</td>";
  print "<td>".stripslashes($a_row->domain)."</td>";
  print "</tr>\n";
}
print "</table>\n";

Both mysql_fetch_array() and mysql_fetch_object() make it easier for you to selectively extract information from a row. Neither of these functions takes much longer than mysql_fetch_row() to execute. Which you choose to use is largely a matter of preference, although mysql_fetch_array() is more commonly used.

    [ Team LiB ] Previous Section Next Section