tags:

views:

33

answers:

2

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 silly..

+4  A: 

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.

prodigitalson
+4  A: 

Hi,

  1. PHP has some interesting interfaces that let you handle objects as arrays. In this case the PDOStatement class implements Traversable and this allows the use of foreach on it. See here http://www.php.net/manual/en/class.pdostatement.php

  2. To 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.

Alin Purcaru