所以我想做的是,我想返回 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/