我是 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/