2011-01-05 215 views
0

我試圖從mysql返回一個計數。我的代碼如下用COUNT(*)返回Mysql結果

$number_of_options_sql = tep_db_query("SELECT COUNT(*) FROM 
(select sum(options_id) as total from products_attributes 
where products_id='".$products_id."' group by options_id) as total"); 
$number_of_options_result = tep_db_fetch_array($number_of_options_sql); 

當我運行在phpMyAdmin此查詢,它顯示了COUNT(*)在表頭的結果。我得到正確的結果,查詢適用於我,我無法將其打印在屏幕上。

我試圖返回值通過以下方式和屏幕上沒有一個打印任何東西:後COUNT(*)

$number_of_options_sql = tep_db_query("SELECT COUNT(*) AS field_name FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) as total"); 

echo $number_of_options_result[COUNT(*)]; 
echo $number_of_options_result[total]; 
+0

缺少行情? – Bobby 2011-01-05 15:58:18

回答

0

您的查詢是將一個別名分配給表/查詢而不是列。使用下面這個:

$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) a"); 
$number_of_options_result = tep_db_fetch_array($number_of_options_sql); 

也像你想知道不同的ID選項的數量爲PRODUCT_ID,我將如下重新編寫查詢:

$number_of_options_sql = tep_db_query("SELECT COUNT(DISTINCT options_id) as total FROM products_attributes WHERE products_id='".$products_id."'"); 
+0

重寫查詢對我來說非常合適。謝謝! – Ryan 2011-01-05 16:13:03

2

使用AS field_name要打印:

echo $number_of_options_result['field_name']; 

(將「field_name」替換爲您的菜單的任何相關名稱CE)

0

只要編輯您的查詢

SELECT COUNT(*) as count FROM .... 

那麼它將被保存,如「計數」,你可以打印在$ number_of_options_result [統計]辦法。

0

放於一個變量「總」

$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total 

然後它

echo $number_of_options_result['total'];