我想在多页上显示评论,所以我想从数据库的1页上选择评论,并在所有其他页面上包括这些评论。
我可以选择并显示每个评论,但是某些帖子没有评论。现在,我在没有评论的情况下收到每个帖子的错误。 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;
答案 0 :(得分:0)
在调用它之前定义空数组。当您运行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
}
}