Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset cursor position in PDO

Tags:

php

mysql

pdo

$data=$stmt->fetchAll(); //Dumping the data shows the result. It is also setting the cursor at the end

while($data=$stmt->fetch())
{
//Does not enters loop
//If fetchAll() removes it work as usual
}

I know It dont need to fetch data twice. But my main question is How to reset cursor position in PDO?

like image 523
varuog Avatar asked Feb 18 '23 09:02

varuog


1 Answers

AFAIK there is no possibility to reset cursor position with PDO - that might something to do with compatibility with some databases, that don't support resetting internal cursors.

If you want to iterate twice over the results, fetch it to the array and iterate over this array:

<?php 
$results = $stmt->fetchAll();  
foreach($results as $row) {
    // first
}

foreach($results as $row) {
    // second
}

Edit Some databases support scrollable cursors. To use that, add PDO::CURSOR_SCROLL flag to prepare method (see examples at PDOFetch documentation page). But that only adds possibility to move forward or backward, not rewind completely. Also, not all databases support that type of cursor (e.g. MySQL doesn't).

like image 120
leafnode Avatar answered Feb 27 '23 22:02

leafnode