我已经厌倦了寻找我的新闻评论系统的解决方案。 是)我有的。 我有2个不同的mysql表项(id,title,category_id,details)和注释(id,item_id,comment) 如果我有单个新闻,那么计数就好了,如图所示: Single news
代码:
if (!empty($comments)) {
$comm = count($comments);
} else {
$comm = 0;
}
但如果我使用相同的代码类别视图,结果是: Category view
如果我使用代码:
$sqls = mysql_query("SELECT c.item_id,
COUNT(c.comment)
FROM comments c
RIGHT JOIN items i
ON c.item_id = i.id
GROUP BY c.item_id");
$comm = mysql_num_rows($sqls);
$smarty->assign('comm',$comm);
结果是:一些评论
如何查看类别查看正确的评论数量?
答案 0 :(得分:0)
尝试这个例子。结果与下面的屏幕截图相同,但有一些背景颜色来区分差异。当然,您应该更改为自己的连接和布局。
<?php
$db = new PDO('sqlite:news.db');//change to your own
$sql = $db->prepare("
SELECT item.id, item.title, item.details, comments.comment, COUNT(comments.id) AS NumberOfComment
FROM item LEFT JOIN comments ON item.id = comments.item_id
GROUP BY item.id ORDER BY item.id");
$sql->execute();
$row = $sql->fetchAll();
//get comment
$comment = $db->prepare("SELECT comment FROM comments WHERE item_id = ?");
foreach ($row as $rows){
echo "<br>";
echo "Title: ".$rows['title'];
echo "<br>";
echo "Details: ".$rows['details'];
echo "<br>";
echo "<i>".$rows['NumberOfComment']." comments </i>";
echo "<br>";
$comment->execute(array($rows['id']));
$comments = $comment->fetchAll();
echo '<div style="background-color:pink;">';
foreach ($comments as $showcomment){
echo $showcomment['comment'];
echo "<br>";
}
echo "</div>";
echo "<br>";
}
?>
示例项目表
示例评论表
,结果是......