问题
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?
回答1:
PDOStatement implements Traversable interface, which means it can be used inside a foreach
loop.
来源:https://stackoverflow.com/questions/41426691/pdostatement-in-foreach-loop-php