当有多个行时,PDO和MySql循环仅输出一行


PDO and MySql loop outputs only one row when there are several

$stmt = $conn->prepare($sql);
$stmt->execute($array);
$rows = $stmt->rowCount();
    if($rows >= 1) {
        $x = $stmt->fetch();
        echo '<div>'.$x['heading'].'</div>';
        while($row = $stmt->fetch()) {
            echo '<div>'.$row['article'].'</div>';
        }
    } else {
        echo 'Nothing found';
    }

像上面这样做时,你能明白为什么循环只输出一行而有几行吗?当我使用两次fetch时,就会发生这种情况。

另外,我怎样才能避免在那里使用两次fetch?它被提取一次,我可以再次使用相同的提取数据吗?

$stmt->fetchAll()

也许这个?

可以使用 fetchAll() 将结果集中的所有数据作为数组获取。

您可以通过将数据分配给变量来重用数据:

// Fetch all returned rows
$my_rows = $stmt->fetchAll();
// Make use of these rows multiple times
foreach ($my_rows AS $single_row)
{
    echo $single_row['column_name'];
}
// Make use of the retult set a second time
foreach ($my_rows AS $single_row)
{
    echo $single_row['column_name'];
}