脚本宝典收集整理的这篇文章主要介绍了php – fetchall()之后的PDO fetchObject().返回假,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
$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()); }
PDOStatement::fetch()
方法及其表兄fetchAll()返回false.文档说它在失败时返回false,缺少可用行计为失败.
您对fetchAll()的初始调用将获取PDOstatement结果对象中的所有行,并且fetchObject()调用不再需要检索,因此返回false.
您只需要初始调用fetchAll(),但如果之前没有为连接设置默认提取类型,则可能需要将其提取类型设置为PDO :: FETCH_OBJ.
然后,您可以在已有的$rows数组上使用简单的foreach循环替换while循环.这样做的另一个好处是可以将显示逻辑与数据库查询业务逻辑分开一点:
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中具有特殊含义的编码是正确编码的,如果这些值来源于用户输入,则可以避免跨站点脚本漏洞.
以上是脚本宝典为你收集整理的php – fetchall()之后的PDO fetchObject().返回假全部内容,希望文章能够帮你解决php – fetchall()之后的PDO fetchObject().返回假所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。