我正在尝试让我的文章获取它有多少评论,并显示数字。这是代码:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE id='" . mysql_real_escape_string($_GET['articleid']) . "'");
$comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT id, news_title, news_content, news_date, news_author FROM articles ORDER BY id DESC LIMIT 5");
while($row = mysql_fetch_array($grab)){
?>
<div class="pane">
<li>
<h2><?php echo $row['news_title'] ?></h2>
<div class="meta">
<span class="color"> • </span>
<?php echo $row['news_date'] ?>
<span class="color"> • </span>
</div>
Comments: <?php echo $comments ?>
但由于某种原因,它保持在“0”。这就是它的样子:
我的专栏是id,articleid,name,comment,date&amp; IP
答案 0 :(得分:0)
你的where子句正在寻找id = articleid。
你想要的是articleid = articleid。
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['articleid']) . "'");
答案 1 :(得分:0)
看起来SQL有问题。检查你的articleid GET变量。另外,对于每篇文章的评论,它不应该为每个文章的评论做不同的查询和mysql_num_rows,因为每篇文章可能包含不同数量的评论。
试试这个:
SELECT
articles.id, news_title, news_content, news_date, news_author
(SELECT COUNT(*) FROM comment WHERE comment.id=articles.id) as comments
FROM articles
ORDER BY id DESC LIMIT 5
这将为您提供前5篇文章及其相关评论。
答案 2 :(得分:0)
您可以使用单个查询。
$grab = mysql_query(
"SELECT a.id, a.news_title, a.news_content, a.news_date, a.news_author, count(*) as comment_count
FROM articles a
LEFT JOIN comment c ON c.articleid = a.id
ORDER BY a.id DESC LIMIT 5 GROUP BY a.id");
然后代替
Comments: <?php echo $comments ?>
执行:
Comments: <?php echo $row['comment_count']; ?>
如果查询有效,请告诉我,我不确定Group by是否正确放置在那里。