2012-02-11 36 views
-1

嘿,我知道php/mysql,我想知道如何計算每個線程的評論,並回顯線程旁邊的數字。 基本上,我每頁顯示25個線程標題,當您點擊它們時,它會將您帶到顯示所有相關注釋的頁面。我試圖簡單計數與「id」匹配的評論「comment_id」,並在標題旁邊回顯它們,所有這些都在一個while循環中進行。 只是讓我知道你需要什麼信息來幫助我,我會盡快發佈。 謝謝。我如何評論每個線程,並回應結果?

回答

0

我們需要知道相關的表的結構,能夠給你一個明確的答覆,但查詢應該是這樣的 -

SELECT thread.id, thread.title, COUNT(comment.id) AS comment_count 
FROM thread 
LEFT JOIN comment 
    ON thread.id = comment.thread_id 
GROUP BY thread.id, thread.title 

這是一個相當原始的例子,我有沒有嘗試運行它,但它應該沒問題 -

<?php 

$dsn = 'mysql:dbname=testdb;host=127.0.0.1'; 
$user = 'dbuser'; 
$password = 'dbpass'; 

try { 
    $dbh = new PDO($dsn, $user, $password); 
} catch (PDOException $e) { 
    echo 'Connection failed: ' . $e->getMessage(); 
} 


$sql = 'SELECT thread.id, thread.title, COUNT(comment.id) AS comment_count 
    FROM thread 
    LEFT JOIN comment 
     ON thread.id = comment.thread_id 
    GROUP BY thread.id, thread.title'; 

$results = $dbh->query($sql); 

while ($row = $results->fetchObject()) { 

    print "<a href=\"show_thread.php?thread_id={$thread->id}\">{$row->title} ({$row->comment_count})</a><br />\n"; 

} 

?> 
+0

我將如何迴應結果? – 2012-02-11 01:01:32

+0

你到目前爲止得到了什麼代碼? – nnichols 2012-02-11 01:11:43

+0

'$ comment_query = mysql_query(「SELECT COUNT(*)FROM wall WHERE comment_id = {$ current_thread}」); while($ comment_result = mysql_fetch_array($ comment_query)){ \t \t echo $ comment_result [0];' 是什麼最終爲我工作,感謝您的幫助。 – 2012-02-11 01:28:52