本文介绍了重置 PDO 结果中的数组指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法从 MySQL SELECT 方法转移到 PDO 方法.我想遍历获取的数组两次,两次都从第 0 行开始.在 MySQL 中,我会使用:
I'm having trouble moving from MySQL SELECT methods to PDO methods. I want to iterate through a fetched array twice, both times starting with row zero. In MySQL I would use:
mysql_data_seek($result,0);
使用 PDO 方法,我不确定如何完成同样的事情.下面的代码是我尝试执行此操作的方式.第一个 while 循环工作正常,但第二个 while 循环什么也不返回.
Using PDO methods, I'm not sure how to accomplish the same thing. The code below is how I am trying to do this. The first while loop works fine but the second while loop returns nothing.
$pdo = new PDO('mysql:host=' . $host . ';dbname='.$database, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE active = 1 ORDER BY name ASC');
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
while($row = $stmt->fetch())
{
//do something starting with row[0]
}
while($row = $stmt->fetch())
{
//do something else starting with row[0]
}
推荐答案
将结果保存到一个数组中,然后将该数组循环两次.
Save your results to an array and then loop that array twice.
$pdo = new PDO('mysql:host=' . $host . ';dbname='.$database, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE active = 1 ORDER BY name ASC');
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $r) {
// first run
}
foreach ($rows as $r) {
// seconds run
}
这篇关于重置 PDO 结果中的数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!