我已经在 mySQL 中检查了下面的 SQL,它返回了用户拥有的正确产品数量。我试图将语句移动到 PHP 中以根据产品计数执行条件代码。然而, echo 总是返回 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;
最佳答案
以这种方式使用 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;
关于php - MySQL 计数匹配行数总是返回 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21760947/