php - 在 fetchall() 之后的 PDO fetchObject()。返回错误

标签 php pdo

我是 PHP 新手。 我正在尝试以表格形式显示员工的详细信息。 但是 while($row = $result->fetchObject()) 部分没有执行,因为 $result->fetchObject() 返回 false。它与 $rows = $result->fetchAll(); 有关系吗? 这是代码片段。

$sql = "SELECT id, name, designation FROM employees";

if ($result = $pdo->query($sql)) {
    $rows = $result->fetchAll();
    $num_rows = count($rows);

    if ($num_rows > 0) {
        echo "<table>\n";
        echo " <tr class=\"heading\">\n";
        echo " <td>ID</td>\n";
        echo " <td>Name</td>\n";
        echo " <td>Designation</td>\n";    
        echo " </tr>\n";

        while($row = $result->fetchObject()) {
            echo " <tr>\n";
            echo " <td>" . $row->id . "</td>\n";
            echo " <td>" . $row->name . "</td>\n";
            echo " <td>" . $row->designation . "</td>\n";
            echo " </tr>\n";
        }
        echo "</table>";
    } else {
        echo "No employees in database.";
    }

else {
    echo "ERROR: Could not execute $sql. " . print_r
    ($pdo->errorInfo());
}

最佳答案

PDO 的文档对此有点困惑,但是 PDOStatement::fetch() 方法及其表亲 fetchAll()返回 false当没有更多行可返回时。文档说它返回 false 失败,并且缺少可用行算作失败。

您最初调用 fetchAll()PDOstatement 中获取所有行结果对象并且没有更多的 fetchObject()调用检索所以它返回 false .

您只需要初次调用 fetchAll() , 但您可能需要将其提取类型设置为 PDO::FETCH_OBJ如果您之前没有为您的连接设置默认的提取类型。

然后,您可以替换您的 while用一个简单的 foreach 循环遍历 $rows你已经拥有的数组。这具有将显示逻辑与数据库查询业务逻辑进一步分离的额外好处:

if ($result = $pdo->query($sql)) {
    // Fetch them now, as objects
    $rows = $result->fetchAll(PDO::FETCH_OBJ);
    $num_rows = count($rows);

    if ($num_rows > 0) {
        echo "<table>\n";
        echo " <tr class=\"heading\">\n";
        echo " <td>ID</td>\n";
        echo " <td>Name</td>\n";
        echo " <td>Designation</td>\n";    
        echo " </tr>\n";

        // $rows now has everything you need, just loop over it
        foreach ($rows as $row {
            echo " <tr>\n";
            echo " <td>" . htmlspecialchars($row->id) . "</td>\n";
            echo " <td>" . htmlspecialchars($row->name) . "</td>\n";
            echo " <td>" . htmlspecialchars($row->designation) . "</td>\n";
            echo " </tr>\n";
        }
        echo "</table>";
    } else {
        echo "No employees in database.";
    }

else {
    echo "ERROR: Could not execute $sql. " . print_r
    ($pdo->errorInfo());
}

另请注意,我添加了对 htmlspecialchars() 的调用在将输出写入 HTML 时。始终建议这样做,以便像 < > & 这样的字符在 HTML 中具有特殊含义的值被正确编码,如果这些值源自用户输入,则可以避免跨站点脚本漏洞。

关于php - 在 fetchall() 之后的 PDO fetchObject()。返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124156/

相关文章:

php - 使用 PHP/PDO 设置 NULL 值

PHP PDO 查询错误

php - 使用 cron 设置提醒系统

php - WP 查询获取具有特定 term_taxonomy 的帖子

php - 页面是否可能知道已使用header()重定向到该页面?

php - 如何在 PHP 中更改 PDO/SQLite 连接的字符编码?

php - MySQL 多重连接并使用结果连接另一个表

PHP 接口(interface) mysql() 不工作,但 mysqli() 工作;为什么?

php - 如何根据条件向数组添加一些项目?

mysql - PDO异常 : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known