重置光标在PDO中的位置


Reset cursor position in 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
}

我知道它不需要两次获取数据。但我的主要问题是如何重置光标位置在PDO?

恐怕PDO无法重置游标位置——这可能与某些数据库的兼容性有关,这些数据库不支持重置内部游标。

如果要在结果上迭代两次,则将其获取到数组中并遍历该数组:

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

Edit一些数据库支持可滚动游标。要使用它,将PDO::CURSOR_SCROLL标志添加到prepare方法(参见PDOFetch文档页面的示例)。但这只能增加前进或后退的可能性,而不能完全倒带。而且,并不是所有的数据库都支持这种类型的游标(例如MySQL就不支持)。