在PDO中重置光标位置

时间:2013-02-27 12:04:33

标签: 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
}

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

1 个答案:

答案 0 :(得分:6)

AFAIK不可能使用PDO重置光标位置 - 这可能与某些数据库的兼容性有关,不支持重置内部游标。

如果要对结果进行两次迭代,请将其提取到数组并迭代此数组:

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

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

编辑某些数据库支持可滚动游标。要使用它,请将PDO::CURSOR_SCROLL标记添加到prepare方法(请参阅PDOFetch documentation page处的示例)。但这只会增加前进或后退的可能性,而不是完全倒带。此外,并非所有数据库都支持该类型的游标(例如MySQL不支持)。