我对这些代码片段在 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)
}
关于php变量导致while循环无限循环显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429606/