Retrieving Results of a Query Via PDO


 $result = $db->query(); $result->fetch(PDO_FETCH_ASSOC); 


Finally, reading out results from an SQL query with PDO is done using the standard approach: Send the SELECT query to the server and then use a while loop to iterate over the results. Here, the iteration is done using the fetch() method. As a parameter, you can provide constants such as PDO_FETCH_ASSOC (which returns an associative array) or PDO_FETCH_OBJ (which returns an object). Alternatively, you can use the fetchAll() method and get an array of arrays, so you have all the data at once.

This code uses fetch() and PDO_FETCH_ASSOC to read out all data from the data source.

Retrieving Data Via PDO (pdo_fetch.php; excerpt)
 <table> <tr><th>#</th><th>Quote</th><th>Author</th><th>Year<   /th></tr> <?php   try {     $db = new PDO('sqlite:PDOquotes.db');     $result = $db->query('SELECT * FROM quotes');     while ($row = $result->fetch(PDO_FETCH_ASSOC)) {       printf( '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></    tr>',         htmlspecialchars($row['id']),         htmlspecialchars($row['quote']),         htmlspecialchars($row['author']),         htmlspecialchars($row['year'])       );     }   } catch (PDOException $ex) {     echo 'Connection failed: ' . htmlspecialchars       ($ex->getMessage());   } ?> </table> 

NOTE

As of this writing, PDO cannot be considered as stable yet; therefore, it is possible that the application programming interface (API) or behavior of PDO may change in the future. Also, if you try out PDO, be aware that this is still not proven to be as reliable as PHP itself.


What Does PEAR Offer?

The following PEAR packages (among others) offer database abstraction layers and other goodies for database access:

  • DB is the best-known database abstraction layer in PEAR

  • DB_DataObject can create SQL from objects

  • DB_QueryTool offers some help for building SQL queries

  • MDB and MDB2 are also feature-rich database abstraction layers





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net