猿问

PHP从数据库中选择并返回值

我想在多个页面上显示评论,所以我想从一页的数据库中选择评论并将这些评论包含在所有其他页面上。


我可以选择并显示每条评论,但有些帖子没有评论。现在,对于每个没有评论的帖子,我都会收到此错误。Notice: Undefined variable: showComments in ...\comments.php on line 7



选择评论的页面:


class Comment {

          public static function displayComments($postId) {

                  $comments = DB::query('SELECT comments FROM table WHERE post_id=:postid', array(':postid'=>$postId);

                  foreach($comments as $comment) {

                          $showComments[] = $comment['comment'];

                  }

                          return $showComments;//this is line 7

          }

}

其他页面:


$postOutput = "postImg, postLikes, postLikeButton";


if(Comment::displayComments($post['id']) >= 1) {

           $comments = Comment::displayComments($post['id']);

           foreach ($comments as $comment) {

                   $postOutput .= $comment;

           }

}


$postOutput .= "postCommentForm";

echo $postOutput;


白衣非少年
浏览 227回答 1
1回答

当年话下

在调用它之前定义空数组。当您运行 foreach 循环时,检查空条件。现在会发生什么,您没有从查询中获得评论,这就是发生这种情况的原因。试试这个。class Comment {          public static function displayComments($postId) {                  $showComments = array(); //this sould be defined in your code                  $comments = DB::query('SELECT comments FROM table WHERE post_id=:postid', array(':postid'=>$postId);              if(!empty($comments)){ //check not empty condition.                  foreach($comments as $comment) {                          $showComments[] = $comment['comment'];                  }              }          return $showComments;//this is line 7          }}
随时随地看视频慕课网APP
我要回答