为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
白衣非少年 2022-01-24 09:20:40
我想在多个页面上显示评论,所以我想从一页的数据库中选择评论并将这些评论包含在所有其他页面上。我可以选择并显示每条评论,但有些帖子没有评论。现在,对于每个没有评论的帖子,我都会收到此错误。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;
查看完整描述

1 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

在调用它之前定义空数组。当您运行 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

          }

}


查看完整回答
反对 回复 2022-01-24
  • 1 回答
  • 0 关注
  • 226 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号