2013-01-20 59 views
2

我很困惑這些代碼片段在while循環中顯示結果的方式不同。代碼的第一部分完美地工作,但第二部分顯示結果,但在無限循環中這樣做,只是重複結果。有人可以向我解釋爲什麼?php變量結果while循環顯示無限循環中的數據

$stmt = $db_conn->prepare($sql); 

$stmt->execute(array("Lorna", 3)); 

while($result = $stmt->fetch()){ 
    echo $result["name"] . "<br />" . $result["description"] . "<br />";   
} 

如果我把$ stmt-> fetch()方法爲一個變量名爲$數據並試圖通過這個,而不是僅僅在while循環將$ stmt-> fetch()方法,我得到一個無限循環。

$stmt = $db_conn->prepare($sql); 

$stmt->execute(array("Lorna", 3)); 

$data = $stmt->fetch(); 

while($result = $data){ 
    echo $result["name"] . "<br />" . $result["description"] . "<br />";   
} 

在此先感謝!

回答

2

如果是致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) 
} 
2

在第一代碼段,每個時間while被調用時,將查詢結果指針移動到新的一行。最終指針將到達結果集的末尾,並且$stmt->fetch()將返回false並結束循環。

在第二個循環中,您只循環一次 - 在循環之前。循環將重複迭代相同的循環,因爲沒有任何變化,所以循環條件從不返回假。

1

第一個循環檢查從函數返回的值可能爲null導致循環結束。

第二個循環只是做一個任務。