0

I want to display comments on multiple pages, so I want to select the comments from the database on 1 page and include those comment on all the other pages.

I can select and display each comment, but some post's don't have comments. Now I get this error for each post without comments. Notice: Undefined variable: showComments in ...\comments.php on line 7


The page to select the comments:

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
          }
}

Other pages:

$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;

1 Answers1

0

Define empty array before you called it. And while you run foreach loop check empty condition. Right now what happens you're not getting comments from a query that's why this is happening. Try this.

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
          }
}
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49