PDOStatement in foreach loop php

浪尽此生 提交于 2021-02-11 08:21:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!