PHP Database Access
Retrieving Rows Without a Loop
Problem
You want a concise way to execute a query and retrieve the data it returns.
Solution
Example Getting all results at once
$st = $db->query('SELECT planet, element FROM zodiac');
$results = $st->fetchAll();
foreach ($results as $i => $result) {
print "Planet $i is {$result['planet']} <br/>\n";
}
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.
No comments:
Post a Comment