首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在php中获取每个帖子的总评论?

如何在php中获取每个帖子的总评论?
EN

Stack Overflow用户
提问于 2019-06-27 02:22:36
回答 1查看 123关注 0票数 -1

我有一个名为comments的表。从这里,我想要显示每个帖子的总评论。我试过了,但它显示了所有帖子的全部评论。但我只想要每个帖子的总评论

代码语言:javascript
复制
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'];
           }
        }
    }

我有一个名为comments的表。从这里,我想要显示每个帖子的总评论。我试过了,但它显示了所有帖子的全部评论。但我只想要每个帖子的总评论。

EN

回答 1

Stack Overflow用户

发布于 2019-06-27 03:06:29

代码语言:javascript
复制
//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";
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56778948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档