【问题标题】:how to get total comment in php for each post?如何获得每个帖子的 php 总评论数?
【发布时间】:2019-06-26 18:22:36
【问题描述】:

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

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'];
           }
        }
    }

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

【问题讨论】:

  • 那么 sql 返回什么?
  • WHERE post_id = `post_id`"; 看起来不太对劲。你可能是说WHERE post_id = 1?或其他数字
  • 您只是检查该行的 post_id 是否等于该行的 post_id。 every 行显然是这种情况。您应该将 $postId 传递到您的函数中,并在查询中使用绑定参数。
  • @Qirel 是的朋友
  • 也许您正在寻找GROUP BY post_id?从你的问题中不清楚你想要的结果是什么。您展示了一些示例数据以及该数据的结果应该是什么。

标签: php mysql sql mysqli


【解决方案1】:
//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";
    }
}

【讨论】:

  • 这是一个答案吗?您需要解释您发布的内容。
  • @Dharman 实际上我正在寻找特定帖子的 cmets 计数。但是当我使用您尝试过的这段代码时,它显示了这个结果,在我的表格中我总共有 9 个帖子,从这篇帖子中我正在寻找特定帖子的 cmets 计数。就是这样。 7 总评论 = 19 总评论 = 142 总评论 = 145 总评论 = 7
  • @Zobair - 我做了一些调整,这样你就可以获得单个帖子的评论数
  • 我修复了你的 PHP 语法错误,但是这个答案仍然存在问题。 WHERE post_id 看起来不正确。我假设您想改用 prepare 并执行 WHERE post_id=?.
猜你喜欢
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 2021-10-27
相关资源
最近更新 更多