PHP PDO 返回错误的列数

标签 php mysql pdo

所以我想做的是,我想返回 where 子句中的列数。目前正在运行:

$total = $pdo->query('
    SELECT
         COUNT(*)
    FROM
         _TABLENAME_
')->fetchColumn();

echo $total .' Rows Found';
// Outputs 10 if, 10 rows are found.

但是当我尝试使用 WHERE LIKE 原因执行此操作时,它不会起作用。

$gr = '%'.$_GET['genres'].'%';
$total = $pdo->query('
    SELECT
         COUNT(*)
    FROM
         _TABLENAME_
    WHERE
         genres
    LIKE
         '.$gr.'
')->fetchColumn();

echo $total . ' Rows Found';
// Outputs 1, even if more are found

但显然这行不通,因为这不是您制作 PDO 执行语句的方式,所以我尝试这样做:

$gr = '%'.$_GET['genres'].'%';
$sql = 'SELECT COUNT(*) FROM `_TABLENAME_` WHERE genres LIKE :gr ';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':gr', $gr, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();

echo $total . ' Rows Found';

但结果还是只有 1。

最佳答案

正如 PHP 手册所说:

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.

相反

use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

在这里查看:Counting rows returned by a SELECT statement 。 在 PHP 手册中,您可以了解更多用例:)

我希望这可以帮助您理解这种行为。

关于PHP PDO 返回错误的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39775882/

相关文章:

mysql - 从多属性搜索的条件中删除搜索字符串/查询属性。从 where 条件中删除空白参数的空白属性

mysql - 是否可以在 SELECT 语句中计算日期范围?

php - 未定义的属性,PDOException 错误

javascript - $$var(在 php 中)等同于 javascript

php - PHP 的 Knet 支付网关

php - 无法使用iPage服务器连接到MySQL数据库

PHP、MySQL、PDO 事务 - 调用 commit() 后是否可以使用 rollBack()?

php - 如何在 woocommerce ajax add_to_cart 之后运行我的自定义 ajax?

php - MySQL 选择 IF INNER JOIN

php - 如何使用持久连接在 AWS 中处理 PDO MySQL 故障转移