为什么第二个示例不与第一个示例相同?看看循环的状况。它不是完全相同的条件写作的方式吗?
当无需获得的时候,第一个示例变成了错误。然后停止。但是第二个示例永远不会变成错误,它不断用结果填充屏幕,并且永远不会完成。无尽的循环。
为什么这些示例的行为会有所不同,且不完全相同?
//First ex
while ($rows = mysqli_fetch_assoc($query)) {
print_r($rows);
}
//second ex
$rows = mysqli_fetch_assoc($query);
while ($rows) {
print_r($rows);
}
//First ex
while ($rows = mysqli_fetch_assoc($query)) {
print_r($rows);
}
这将在每次迭代中执行,因此在每次迭代中将下一个值放置在$row
中。
//second ex
$rows = mysqli_fetch_assoc($query);
while ($rows) {
print_r($rows);
}
在上面的代码中,您仅将第一个迭代值放在$row
上。$row
在每次迭代时都没有更新。所以这将永远运行。
结论:
每次致电
mysqli_fetch_assoc($query)
时,都会给出下一行。
在第一个示例中,$ row在每次迭代中一次又一次调用mysqli_fetch_assoc($query)
在每次迭代中都有下一行。
在第二个示例中, mysqli_fetch_assoc($query)
仅被调用一次。因此,您的$row
每次运行时都有价值,因此它将在无限的时间内运行。
首先,每个循环都会获取mysql数据。因为条件内部检查的语句将运行每个检查。第二个仅运行一次。
第二个语句目前在while(condition){}
内没有条件,您刚刚声明了一个变量。因此,它不会以与第一个语句相同的方式执行。
//mysql users table
//id | nick | date
//1 | x1 | 2018-01-05
//2 | x2 | 2018-01-06
//3 | x3 | 2018-01-07
while ($row = mysqli_fetch_assoc($query)) {
print_r($row);
}
//first loop call row one
//second loop call row two
//third loop call row three
print_r(mysqli_fetch_assoc($query)); //print row one and mysql cursor jump to row two
print_r(mysqli_fetch_assoc($query)); //print row two and mysql cursor jump to row there
print_r(mysqli_fetch_assoc($query)); //print row there
//but mysqli_fetch_assoc bring one row not rows
$row = mysqli_fetch_assoc($query);
//row is null, no print and repeat
//row is null, no print and repeat
//row is null, no print and repeat
//row is null, no print and repeat
// ∞ :))
while ($row) {
print_r($row);
}