qazerty23
qazerty23

Reputation: 491

PDOStatement in foreach loop php

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

Answers (1)

Yury Fedorov
Yury Fedorov

Reputation: 14928

PDOStatement implements Traversable interface, which means it can be used inside a foreach loop.

Upvotes: 2

Related Questions