我有一个名为comments的表。从这里,我想要显示每个帖子的总评论。我试过了,但它显示了所有帖子的全部评论。但我只想要每个帖子的总评论
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的表。从这里,我想要显示每个帖子的总评论。我试过了,但它显示了所有帖子的全部评论。但我只想要每个帖子的总评论。
发布于 2019-06-27 03:06:29
//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";
}
}
https://stackoverflow.com/questions/56778948
复制相似问题