2014-02-13 23 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时()?