首页 > 解决方案 > 调用未定义的方法 PDO::fetchAll()

问题描述

信息正在从数据库发送,但这并没有在我的网站中显示,我收到此错误:

致命错误:未捕获错误:调用 /storage/ssd1/525/6600525/public_html/ajax_message_forms/fetch_comment.php:14 中未定义的方法 PDO::fetchAll() 堆栈跟踪:#0 {main} 在 /storage/ssd1/ 中抛出第 14 行的 525/6600525/public_html/ajax_message_forms/fetch_comment.php

<?php

$connect = new PDO('mysql:host=localhost;dbname=xx' ,'xx' ,'xx');
$query = "
SELECT * FROM tbl_comment 
WHERE parent_comment_id = '0' 
ORDER BY comment_id DESC
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $connect->fetchAll();
$output = '';
foreach($result as $row)
{
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
  <div class="panel-body">'.$row["comment"].'</div>
  <div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
 </div>
 ';
 $output .= get_reply_comment($connect, $row["comment_id"]);
}

echo $output;

function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
 $query = "
 SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
 ";
 $output = '';
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $count = $statement->rowCount();
 if($parent_id == 0)
 {
  $marginleft = 0;
 }
 else
 {
  $marginleft = $marginleft + 48;
 }
 if($count > 0)
 {
  foreach($result as $row)
  {
   $output .= '
   <div class="panel panel-default" style="margin-left:'.$marginleft.'px">
    <div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
    <div class="panel-body">'.$row["comment"].'</div>
    <div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
   </div>
   ';
   $output .= get_reply_comment($connect, $row["comment_id"], $marginleft);
  }
 }
 return $output;
}

?>

标签: php

解决方案


fetchAll()是对象的方法,PDOStatement在调用时创建并返回$statement = $connect->prepare($query);

这是您需要应用于您的代码的修复程序

$statement->execute();

$result = $statement->fetchAll();
//        ^--------^-----------------This instead of $connect

此查询"SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'"易受SQL 注入攻击考虑使用准备好的语句

例如:

$query = "SELECT * FROM tbl_comment WHERE parent_comment_id = :parent_id";
$statement = $connect->prepare($query);
$statement->bindParam(':parent_id', $parent_id);
$statement->execute();

推荐阅读