2012-07-01 29 views
0

我試圖根據一定的條件計算表中的行數。 所以,我確實設法編寫了一段可以根據需要運行的代碼。有條件的記錄計數

但是,它有點太長了。所以我想知道是否有更簡單的方法來實現它。

代碼:

// Comments 
$sql_total_comments = mysql_query("SELECT * FROM comments"); 
$sql_pending_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '0'"); 
$sql_approved_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '1'"); 
$sql_declined_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '2'"); 

$total_comments_num = mysql_num_rows($sql_total_comments); 
$pending_comments_num = mysql_num_rows($sql_pending_comments); 
$approved_comments_num = mysql_num_rows($sql_approved_comments); 
$declined_comments_num = mysql_num_rows($sql_declined_comments); 

回答

1

使用COUNT() DB函數來完成這樣的工作。

$ret = mysql_query("SELECT COUNT(*) FROM comments"); 
$row = mysql_fetch_row($ret); 
$total_comments_num = $row[0]; 
+0

而如何將我叫懸而未決的NUM,批准和拒絕?我是否必須重新編寫並提供WHERE? - 有點新的PHP和仍在學習。 :) – Khaled

+0

這是後我的結果(總評論:4 - 提出的意見:1 - 已批准評論:2 - 拒絕評論:1) – Khaled

+0

@Khaled是的,就是這樣。 – xdazz

0

使用select count(*) from comments where .....

2
SELECT comment_status, COUNT(comment_status) 
    FROM comments GROUP BY comment_status; 

在代碼中,無論是總的計數彌補總數或運行COUNT(*),如其他答案一個單獨的查詢。

所以您的代碼會是這個樣子,假設你使用PDO:

$sql = 'SELECT comment_status, COUNT(comment_status) AS "count" '. 
    'FROM comments GROUP BY comment_status;'; 
$query = $db->query($sql); 
$count_total = 0; 
$count = array(); 
while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) { 
    $count_total += $row['count']; 
    $count[$row['comment_status']] += $row['count']; 
} 
$query = null; // Because I'm neurotic about cleaning up resources. 
+0

感謝您的幫助,但事情是..這是一個正在學習PHP的項目,並且您寫下的代碼對我來說仍然是不可讀的。所以,我會堅持現在xdazz的解釋。但是,再次感謝您的意見。讚賞。 – Khaled

+1

PDO看起來有點嚇人,但它在很多方面都更好,實際上並不像看起來那麼難。只需[連接](http://www.php.net/manual/en/pdo.construct.php),[查詢](http://www.php.net/manual/en/pdo.prepare.php) ,和[抓取](http://www.php.net/manual/en/pdostatement.fetchall.php)你的結果。 –

+0

我會看看它,謝謝指出它。 – Khaled