繁体   English   中英

While循环条件php

[英]While loop condition php

为什么第二个示例与第一个示例的工作方式不同? 查看循环的条件。 是不是条件完全相同,只是书写方式不同?

当没有其他东西可得到时,第一个示例将变为false。 然后停止。 但是第二个示例永远不会出错,它会不断向屏幕填充结果,并且永远不会完成。 无休止的循环。

为什么这些示例的行为不同而又不完全相同?

//First ex
while ($rows = mysqli_fetch_assoc($query)) {
print_r($rows);
}



//second ex
$rows = mysqli_fetch_assoc($query);
while ($rows) {
print_r($rows);
}

第一个将在每个循环中获取mysql数据。 因为条件检查中的语句将运行每个检查。 第二个只运行一次。

第二个while语句在while(condition){}没有条件while(condition){}现在您刚刚声明了一个变量。 因此,它的执行方式与第一条语句不同。

//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 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM