fetchall()之后的PDO fetchObject()。返回假

时间:2014-01-14 21:13:25

标签: 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());
}

1 个答案:

答案 0 :(得分:7)

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());
}

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