tags:

views:

886

answers:

3

I'm trying to write an iterator for results from a PDO statement but I can't find any way of rewinding to the first row. I would like to avoid the overhead of calling fetchAll and storing all the result data.

// first loop works fine
foreach($statement as $result) {
    // do something with result
}

// but subsequent loops don't
foreach($statement as $result) {
    // never called 
}

Is there some way of reseting the statement or seeking the first row?

+1  A: 

You'll probably want to take a look at some of the PHP SPL classes that can be extended to provide array-like access to objects.

Noah Goodrich
PdoStatement already implements Traversable
troelskn
+2  A: 

I'm pretty sure this is database dependent. Because of that, it is something you should try to avoid. However, I think you can achieve what you want by enabling buffered queries. If that doesn't work, you can always pull the result into an array with fetchAll. Both solutions have implications for your applications performance, so think twice about it, if the resultsets are large.

troelskn
+2  A: 

see slide 31 from this presentation, you can do a $statement->rewind() if it applies to a buffered query. If you use mysql, you can emulate buffered queries by using PDO_MYSQL_ATTR_USE_BUFFERED_QUERY:

$pdo->setAttribute(PDO_MYSQL_ATTR_USE_BUFFERED_QUERY, 1);

gabriel1836 pointed you to spl. Here is an example that always works:

$it = new ArrayIterator($stmt->fetchAll());
Exception e