PHP变量导致while循环在无限循环中显示数据


php variable results in while loop displaying data in infinite loop

我对这些代码片段在while循环中显示结果的不同感到困惑。第一个代码片段工作得很好,但是第二个代码片段显示结果,但是是在无限循环中进行的,并且只是重复结果。有人能给我解释一下吗?

$stmt = $db_conn->prepare($sql);
$stmt->execute(array("Lorna", 3));
while($result = $stmt->fetch()){
    echo $result["name"] . "<br />" . $result["description"] . "<br />";        
}

如果我将$stmt->fetch()放入一个名为$data的变量中,并尝试传递它,而不是将$stmt->fetch()放入while循环中,我会得到一个无限循环。

$stmt = $db_conn->prepare($sql);
$stmt->execute(array("Lorna", 3));
$data = $stmt->fetch();
while($result = $data){
    echo $result["name"] . "<br />" . $result["description"] . "<br />";        
}

提前感谢!

这是对fetch()的调用,它使行前进。

案例1

while($result = $stmt->fetch()){
    //every iteration executes fetch
    //advances it by one row
    //turns to false when no more rows
}

案例2

$data = $stmt->fetch();
//now at first row
while($result = $data){
    //always at first row 
    //always evaluates to true (no calls to fetch)
}

在第一个代码片段中,每次调用while时,查询结果指针移动到新行。最后指针将到达结果集的末尾,$stmt->fetch()将返回false并结束循环。

在第二个循环中,只迭代到下一行一次——在循环之前。然后循环将一次又一次地迭代相同的循环,因为没有任何变化,所以循环条件永远不会返回false。

第一个循环检查从函数返回的值是否为空,该值可能导致循环结束。

第二个循环只是赋值。