PHP/PDO: return query rows without foreach?
I am confused about this, I run a query such as
foreach($dbh->query("SELECT * FROM ...") as $row) {
...do something with row()
But when I var_dump $dbh
it is a PDOstatement object.
This leads me to two questions:
- How does foreach somehow resolve the object into separate rows?
- How can I store all rows in an array, like $arr = $dbh->query(...)? This does not work because it is still an object
I can of course run under the foreach, and do $arr[] = $row, but that seems a bit s开发者_JAVA百科illy..
PHP has some interesting interfaces that let you handle objects as arrays. In this case the
PDOStatement
class implementsTraversable
and this allows the use offoreach
on it. See here http://www.php.net/manual/en/class.pdostatement.phpTo get all your results in one array take a look at PDOStatement::fetchAll. And also in the future consider checking the PHP documentation on php.net if you run into problems. It's packed with examples and useful user comments.
Use PDOStatement::fetchAll()
to get the entire result set as array. AS far as what PDO does internally it uses an iterator to access some representation of a recordset. This way you use less memory because youre not pulling the entire result set into php, youre using something resembling a resource
thats internal to the implementation.
精彩评论