Databases Reference
In-Depth Information
The function that does the actual work is mysql_query( ) , and it takes two parameters:
first, the SQL query, and, second, the database connection resource handle that
identifies the connection to use. It returns a database result resource that is used to
identify the rows to be retrieved in the next step; in this example, it's saved in the
variable $result . Unlike with the MySQL monitor, there's no need to add a semicolon
symbol ( ; ) at the end of the query.
The fourth step retrieves and displays the results; it's the most complicated step and
spans 14 lines in the script:
// Until there are no rows in the result set, fetch a row into
// the $row array and ...
while ($row = @ mysql_fetch_array($result))
{
// Start a table row
print "<tr>\n";
// ... and print out each of the columns
foreach($row as $data)
print "\t<td>{$data}</td>\n";
// Finish the row
print "</tr>\n";
}
It works as follows:
• The while loop fetches each result row, one by one, from the MySQL server using
mysql_fetch_array( ) . The parameter to the function is $result , which references
the results from the query that was executed in the third step. Each row returned
by the function is saved in the variable $row and then processed in the loop body
as detailed next. The loop stops when there are no more rows to retrieve.
• Inside the body of the while loop, three steps occur for each retrieved row:
1. The first print statement produces an HTML <tr> tag to start a new table row.
2. The foreach loop processes each column value for the row and uses a print
statement to surround each column value with <td> and </td> tags.
3. The last print statement produces an HTML </tr> tag to end the row.
Because there are always two columns in every row of output—and they're always in
the same order—the artist_id and artist_name column values line up with the head-
ings, as shown in Figure 13-5. When all of the artists have been printed, the while loop
ends, and the script finishes.
We haven't discussed many of the features of PHP that we've used. For example, the
script has error-handling capabilities, so it'll report a message to the user when some-
thing goes wrong. Statements such as foreach require some explanation, but don't
worry about the details for now. The next two chapters explain all you need to build a
basic application.
 
Search WWH ::




Custom Search