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']);
}
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.