简体   繁体   English

MySQL计数匹配行数总是返回1

[英]MySQL count number of matching rows always returns 1

I've checked the SQL below in mySQL and it returns the correct count of products that the user has. 我已经在mySQL中检查了以下SQL,它返回了用户拥有的正确产品计数。 I'm trying to move the statement into a PHP to execute conditional code based on the product count. 我正在尝试将该语句移到PHP中,以根据产品数量执行条件代码。 However, the echo always returns 1. What am I missing? 但是,回声总是返回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;

You will always get one row returned when using COUNT() this way as you have to get a result set even if the result of COUNT() is zero. 这样使用COUNT()时,总是会返回一行,因为即使COUNT()的结果为零,也必须获得结果集。 Or else how will you know what the results are? 否则您将如何知道结果呢? If you want the results of COUNT() you need to get the results of your query as normal and then check the value of the COUNT() operation. 如果需要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;

What you should do is, get the column. 您应该做的是获取专栏。 PDO have the fetchColumn function which gets the columns. PDO具有获取列的fetchColumn函数。 You should use it instead of $stmt->rowCount() 您应该使用它而不是$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;

Since SQL already fetched the row count why use PDO's rowCount() ? 由于SQL已经获取了行数,为什么要使用PDO的rowCount()?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM