Pdo 警告:在 php 中为 foreach() 提供的参数无效


Pdo Warning: Invalid argument supplied for foreach() in php

我正在尝试使用 PHP 中的 PDO 进行 sql 查询,但出了点问题,我无法弄清楚。

这是我的代码:

    *//Connection file*
    < ? php
    $dsn = 'mysql:host=localhost;dbname=oopdo';
    $db = new PDO($dsn, 'root', '');
    ?>
    *//Index file*
    < ? php
    try{
        require_once 'pdo_connection.php';
        $sql = 'SELECT * FROM names'.
                'ORDER BY name';
    } catch (Exception $ex) {
        $error = $ex->getMessage();
    }

    ?>
<html>
    <head>
    </head>
    <body>
        <h2>Looping direct over SELECT query</h2>
        <table>
            <tr>
                <th>Name</th>
                <th>Meaning</th>
                <th>Gender</th>
            </tr>

            foreach($db->query($sql) as $row){ (line 35)

            <tr>
                <td> echo $row['name']; </td>
                <td> echo $row['meaning']; </td>
                <td> echo $row['gender']; </td>
            </tr>
             }
        </table>
    </body>
</html>

警告:第 35 行中为 foreach() 提供的参数无效

我在这里做错了什么?

谢谢。

你真正做错了什么:

尚未检查查询的返回状态,查询失败并出现语法错误。你应该使用这样的代码:

$result = $db->query($sql);
if ($result !== false) {
    foreach($result as $row) {
       // do stuff
    }
} else {
    echo 'The SQL query failed with error '.$db->errorCode;
}

你实际上做错了什么:

将查询拆分为两行的位置,您有意省略一些空格。您的查询提交方式为

SELECT * FROM namesORDER BY name

在字符串中添加一个额外的空格后立即names