簡體   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