Why is the expression in this while loop causing an infinite loop?
New to oop and was just wondering why this causes an infinite loop:
while ($row=$dbh->query("SELECT * FROM animal")->fetch(PDO::FETCH_ASS开发者_高级运维OC)){
printf("A(n) %s is a type of %s<br />", $row['name'], $row['species']);
}
However this does not cause an infinite while loop
$sth=$dbh->query("SELECT * FROM animal");
while ($row=$sth->fetch(PDO::FETCH_ASSOC)){
printf("A(n) %s is a type of %s<br />", $row['name'], $row['species']);
}
In the first code sample you are re-running the query repeatedly in a loop, each time fetching only the first row.
In the second code sample you first run the query once before the loop starts. Then you loop, fetching each row in the result set until there are no more rows.
The parenthesized statement in the while loop gets executed each time. That means that your query starts over each time, so you're always looking at the first object, and so infinite loop!
The second is way more correct.
精彩评论