2015-11-16 57 views
0

我厭倦了尋找我的新聞評論系統的解決方案。 我有什麼。 我有2個不同的MySQL表項(ID,標題,CATEGORY_ID,細節)和評論(ID,ITEM_ID,評論) ,如果我有一個消息則計數是罰款喜歡這裏的圖片: 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

如果可以的話,你應該[停止使用'mysql_ *'功能(http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in -php)。 [這些擴展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中刪除。瞭解[編寫]​​(http://en.wikipedia.org/ wiki/Prepared_statement)語句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli.quickstart .prepared-statements.php)並考慮使用PDO,[它確實不難](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

使用'group by categor_id,item_id'和'select gategory_id,item_id,count(item_id) – Laurentiu

+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>";  
} 
?> 

例如項目表

example table table

例如評語表

example comment table

,其結果是...

result

+0

現在工作正常。謝謝你的時間。 – rainb