$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
}
编辑 一些数据库支持可滚动游标。要使用它,请将 PDO::CURSOR_SCROLL
标志添加到 prepare
方法(参见 PDOFetch documentation page 中的示例)。但这只会增加向前或向后移动的可能性,而不是完全倒带。此外,并非所有数据库都支持该类型的游标(例如 MySQL 不支持)。
关于php - 重置 PDO 中的光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15111681/