Reputation: 491
There is a following code:
<?php
include 'connection.php'; //$db is declared here. It's a PDO object.
foreach ($db->query("SELECT * FROM names") as $row) {
echo $row['firstname'] . $row['lastname'] . $row['postcode'] . '<br>';
}
?>
The code works as expected, but I don't understand the logic behind it.
I've read on php.net that PDO::query()
returns a PDOStatement
object as a result set.
So teoretically, this part: $db->query("SELECT * FROM names")
is a PDOStatement
object.
How does foreach
loop through an PDOStatement
object? Does it convert the PDOStatement
object to an associative array? Why isn't this part: $db->query("SELECT * FROM names") as $row
giving errors?
Upvotes: 1
Views: 275
Reputation: 14928
PDOStatement
implements Traversable
interface, which means it can be used inside a foreach
loop.
Upvotes: 2