开发者

Why is the expression in this while loop causing an infinite loop?

开发者 https://www.devze.com 2023-04-07 06:52 出处:网络
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)){

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号