2013-03-04 57 views
0

我试图让我的文章获取它有多少评论,并显示数字。这里的代码:SQL语法显示日期

<?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"> &bull; </span> 
      <?php echo $row['news_date'] ?> 
      <span class="color"> &bull; </span> 
      </div> 

      Comments: <?php echo $comments ?> 

但由于某种原因,它保持在“0”。这是它的样子:enter image description here

和我的列是id,articleid,名称,注释,日期& ip。

+0

究竟是什么问题? – Jeremy1026 2013-03-04 16:02:06

+0

@ Jeremy1026 - 问题基本上是“为什么'mysql_num_rows()'返回零?” – 2013-03-04 16:02:53

+0

你是否确定articles.id匹配comments.id?这意味着每篇文章最多只能有一条评论。你需要查看表格之间的关系。 – 2013-03-04 16:07:19

回答

0

您的where子句正在查找id = articleid。

你想要的是where articleid = articleid。

$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['articleid']) . "'"); 
+0

嗨凯尔,谢谢你的帮助。但由于某种奇怪的原因,它仍然显示为零。 – TrippedStackers 2013-03-04 16:05:05

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篇文章及相关评论数。

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

让我知道,如果查询工作,我不知道,如果本集团通过正确地放置在那里。

+0

我得到一个布尔错误:警告:mysql_num_rows()期望参数1是资源,在第32行的/home/krissale/public_html/blog/index.php中给出的布尔值将是'$ comment = mysql_num_rows ($ comment_count);'@maltray – TrippedStackers 2013-03-04 16:30:49

+0

http://pastebin.com/CR6eWctC – TrippedStackers 2013-03-04 16:35:33

+0

http://pastebin.com/xU9Ey1ZN尝试并让我知道 – maltray 2013-03-04 16:41:49