05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

For example, this fetches the names of all the Bond movies in the database, ordered<br />

by the year they were released:<br />

$titles = $db->getAll("SELECT title FROM movies ORDER BY year ASC");<br />

foreach ($titles as $title) {<br />

echo "$title\n";<br />

}<br />

Dr No<br />

From Russia With Love<br />

Goldfinger<br />

...<br />

The getAll( ) method returns an array of all the rows returned by the query:<br />

$all = $db->getAll(SQL [, values [, fetchmode ]]);<br />

For example, the following code builds a select box containing the names of the<br />

movies. The ID of the selected movie is submitted as the parameter value.<br />

$results = $db->getAll("SELECT id,title FROM movies ORDER BY year ASC");<br />

echo "\n";<br />

foreach ($results as $result) {<br />

echo "{$result[1]}\n";<br />

}<br />

echo "";<br />

All the get*( ) methods return DB_ERROR when an error occurs.<br />

Details About a Query Response<br />

Four PEAR DB methods provide you with information on a query result object:<br />

numRows( ), numCols( ), affectedRows( ), and tableInfo( ).<br />

The numRows( ) and numCols( ) methods tell you the number of rows and columns<br />

returned from a SELECT query:<br />

$howmany = $response->numRows( );<br />

$howmany = $response->numCols( );<br />

The affectedRows( ) method tells you the number of rows affected by an INSERT,<br />

DELETE, or UPDATE operation:<br />

$howmany = $response->affectedRows( );<br />

The tableInfo( ) method returns detailed information on the type and flags of fields<br />

returned from a SELECT operation:<br />

$info = $response->tableInfo( );<br />

The following code dumps the table information into an HTML table:<br />

$info = $response->tableInfo( );<br />

a_to_table($info);<br />

function a_to_table ($a) {<br />

echo "\n";<br />

foreach ($a as $k => $v) {<br />

200 | Chapter 8: Databases<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!