一尘不染

在PDO结果中重置数组指针

mysql

我无法从MySQL SELECT方法转换为PDO方法。我要遍历两次提取的数组,两次都从零行开始。在MySQL中,我将使用:

mysql_data_seek($result,0);

使用PDO方法,我不确定如何完成同一件事。下面的代码是我试图做到这一点。第一个while循环工作正常,但是第二个while循环不返回任何内容。

$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]
}

阅读 349

收藏
2020-05-17

共1个答案

一尘不染

将结果保存到数组,然后将该数组循环两次。

$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
}
2020-05-17