首页 > 解决方案 > 如何获得每个帖子的 php 总评论数?

问题描述

我有一张带有评论名称的表格。从这里我想显示每个帖子的总评论。我试过了,但它显示了所有帖子的总评论。但我只想要每个帖子的总评论

function commeNT(){
        global $conn;
         $sql = "SELECT COUNT(`post_id`) as `totalComment` FROM `comments` WHERE post_id = `post_id`";
            $result = $conn->query($sql);                    
            if(mysqli_num_rows($result) > 0){
            while($comm= mysqli_fetch_array($result)){                  
            echo $comm['totalComment'];
           }
        }
    }

我有一张带有评论名称的表格。从这里我想显示每个帖子的总评论。我试过了,但它显示了所有帖子的总评论。但我只想要每个帖子的总评论。

标签: phpmysqlsqlmysqli

解决方案


//This will get you a list of all posts and total comments for each.
function all_post_comments() {
    global $conn;
    $sql = "SELECT COUNT(`post_id`) as `totalComment`, `post_id` FROM `comments` GROUP BY `post_id`";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($comm = $result->fetch_array()) {
            echo $comm['post_id'] . ' Total Comments = ' . $comm['totalComment'];
        }
    }
}

//This will get you total comments for a specific post.  You have to pass post id when calling the function.
function comment_count($postId) {
    global $conn;
    $sql = "SELECT COUNT(`post_id`) as `totalComment` FROM `comments` WHERE `post_id` = $postId";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $comm = $result->fetch_array();
        echo $postId . ' Total Comments = ' . $comm['totalComment'];
    } else {
        echo "No Post Found with that id";
    }
}

推荐阅读