php - 如何获得每个帖子的 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'];
}
}
}
我有一张带有评论名称的表格。从这里我想显示每个帖子的总评论。我试过了,但它显示了所有帖子的总评论。但我只想要每个帖子的总评论。
解决方案
//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";
}
}
推荐阅读
- android-studio - java.lang.NullPointerException:findViewById(R.id.contactsList) 不能为空
- mongodb - 如何在 mongodb 中使用查找和 $push
- python - 如何将一条消息发送给多个标记的用户?(discord.py)
- c - 为什么作弊引擎可以访问内存位置而我自己的程序却不能?
- php - 在php上上传图像时出现未定义的数组键错误
- python-3.x - Xlabel 没有出现
- flutter - Flutter 应用程序不会在 Android 上验证应用程序链接
- c# - c#/unity json 错误,并希望使用 Unity JsonUtility 或 litJson 在 JsonObject 中检索 jsonObject
- flutter - 扑动中的可点击单元格
- javascript - 如何比较嵌套对象/数组结构中的特定键值?