繁体   English   中英

输出帖子评论量

[英]Output amount of comments of post

我正在尝试在显示帖子标题的索引页上显示帖子的评论量。

我可以显示索引上的标题,正文,发布者和创建日期,但其注释数量除外。 即使查询设置正确,我也很难从数据库中选择它。

<?php if(empty($posts)): ?>
     <p>There are currently no posts.</p>
   <?php else: ?>

   <?php foreach($posts as $post): ?>

   <div class="post">
    <div class="title"><a href="<?php echo BASE_URL; ?>/post.php?post=<?php echo $post['id']; ?>"><?php echo $post['name']; ?></a></div>
    <div class="short-body"><?php echo $post['body']; ?> <a href="#">Read more</a></div>
    <div class="posted-by">Posted by <?php echo $post['user']; ?></div> <div class="date">On <?php echo $post['created']; ?> 

    | <?php foreach ($comments as $comment): echo $comment[0]; ?>   comments <?php endforeach; ?> </div>
   </div>

   <?php endforeach; ?>

    <?php endif; ?>

除注释数量外,所有内容均通过上述代码显示在页面上。

这是注释代码和其背后的查询:

    $posts = $db->query("SELECT name,body,id,created,user FROM posts ORDER by id DESC")->fetchAll(PDO::FETCH_ASSOC);

    $id = $posts['id'];
    $comments = $db->prepare("SELECT COUNT(*) FROM comments where                                 $post_id=:post_id");
    $comments->execute(['post_id' => $id]);
    $comments = $comments->fetch(PDO::FETCH_NUM);

我确信我的问题是$ id没有被正确使用。 虽然我不知道该放什么。 将post_id分配给帖子的ID,在数据库中存储评论。 我已经尝试了很多东西,但仍然无法正常工作。

我认为您可以通过单个查询来检索帖子信息和评论数量,这应该可以避免您的问题并提高效率; 例如 :

SELECT
  posts.name,
  posts.body,
  posts.id,
  posts.created,
  posts.user,
  count(comments.id) AS comments_count

FROM posts
   LEFT JOIN comments ON comments.post_id = posts.id

GROUP BY posts.id DESC

对于您的原始查询,我认为问题在于$posts包含多行,因此$posts['id']不存在,但是$posts[0]['id']确实存在, $posts[1]['id']等等,如果您想保留原始查询,则应遍历$posts以将评论数与结果中的每个帖子相关联。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM