Recipe 10.5. Retrieving Rows Without a Loop


10.5.1. Problem

You want a concise way to execute a query and retrieve the data it returns.

10.5.2. Solution

Use fetchAll( ) to get all the results from a query at once, as shown in Example 10-13.

Getting all results at once

<?php $st = $db->query('SELECT planet, element FROM zodiac'); $results = $st->fetchAll(); foreach ($results as $i => $result) {    print "Planet $i is {$result['planet']} <br/>\n"; } ?>

10.5.3. Discussion

The fetchAll( ) method is useful when you need to do something that depends on all the rows a query returns, such as counting how many rows there are or handling rows out of order. Like fetch( ), fetchAll( ) defaults to representing each row as an array with both numeric and string keys and accepts the various PDO::FETCH_* constants to change that behavior.

fetchAll( ) also accepts a few other constants that affect the results it returns. To retrieve just a single column from the results, pass PDO::FETCH_COLUMN and a second argument, the index of the column you want. The first column is 0, not 1.

10.5.4. See Also

Recipe 10.6 for querying an SQL database and more information on fetch modes; Recipe 10.6 for modifying an SQL database; Recipe 10.7 for repeating queries efficiently; documentation on PDO at http://www.php.net/PDO.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

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