簡體   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