2014-02-13 32 views
0

我在mySQL中檢查了下面的SQL,它返回用戶擁有的產品的正確計數。我試圖將該語句移入PHP以基於產品計數來執行條件代碼。但是,回聲總是返回1.我錯過了什麼?MySQL計數匹配行數總是返回1

$sql = "select count(product_id) from dap_users_products_jn where product_id not in(13,34) and user_id = 1"; 
$stmt = $dap_dbh->prepare($sql); 
$stmt->execute(); 
$stmt = $stmt->rowCount(); 
echo "the product count is: ".$stmt; 
+0

'rowCount()'不適用於'SELECT'語句。請參閱文檔:http://www.php.net/manual/en/pdostatement.rowcount.php –

+0

您只獲得一行,其中包含product_ids的計數。 – Cyclonecode

+0

是的,你有_1_行,_1_字段,你需要_fetch_看看_value_它是什麼;) – Wrikken

回答

3

你總是會得到使用COUNT()這樣,當你有得到一個結果集即使COUNT()結果是零一行返回。或者你怎麼知道結果是什麼?如果您需要COUNT()的結果,則需要正常查看查詢結果,然後檢查COUNT()操作的值。

$sql = "select count(product_id) AS prod_count from dap_users_products_jn where product_id not in(13,34) and user_id = 1"; 
$stmt = $dap_dbh->prepare($sql); 
$stmt->execute(); 
$result = $stmt->fetch(PDO::FETCH_OBJ); 
echo "the product count is: ".$result->prod_count; 
1

你應該做的是,拿到專欄。 PDO有獲取列的函數fetchColumn函數。你應該用它代替$stmt->rowCount()

$sql = "select count(product_id) from dap_users_products_jn where product_id not in(13,34) and user_id = 1"; 
$stmt = $dap_dbh->prepare($sql); 
$stmt->execute(); 
$stmt = $stmt->fetchColumn(); 
echo "the product count is: ".$stmt; 

由於SQL取出已行數爲什麼使用PDO的rowCount時()?