Ken Ken - 1 year ago 74
PHP Question

Is it possible to rewind a PDO result?

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?

Answer Source

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.