Reputation: 16152
New to oop and was just wondering why this causes an infinite loop:
while ($row=$dbh->query("SELECT * FROM animal")->fetch(PDO::FETCH_ASSOC)){
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']);
}
Upvotes: 0
Views: 323
Reputation: 838806
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.
Upvotes: 5
Reputation: 11899
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.
Upvotes: 3