PHP PDO rowCount returns -1 SELECT 语句
PHP PDO rowCount returns -1 on SELECT statement
我遇到了一个奇怪的问题,一整天都在困扰着我。
我有以下代码:
$today = date("m/d/Y");
$sql = "SELECT * FROM msgs WHERE is_errata = 0 AND kill_date >= '$today' AND msg_date <= '$today' ORDER BY msg_date";
$ps = $pdo->prepare($sql);
if (!$ps) {
echo "PDO::errorInfo():";
print_r($pdo->errorInfo());
}else{
$ps->execute();
$number_of_rows = $ps->rowCount();
当我显示 $number_of_rows 的值时,它总是显示 -1,即使我得到结果也是如此。
还有其他人有这个问题吗?
哦,我使用的数据库不是 MySQL,而是可爱的 MS Access。我怀疑这可能是问题所在。
rowCount()
方法不 return 来自 SELECT
语句的行数。这是常见的错误。
PDOStatement::rowCount() returns the number of rows affected by the
last DELETE, INSERT, or UPDATE statement executed by the corresponding
PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was
a SELECT statement, some databases may return the number of rows
returned by that statement. However, this behaviour is not guaranteed
for all databases and should not be relied on for portable
applications.
您可以在 documentation 中找到更多详细信息。
因此,要获得行数,您必须使用 sql COUNT(*)
函数编写 SELECT
语句。在你的情况下:
$sql = "SELECT COUNT(*) AS `count` FROM msgs WHERE is_errata = 0 AND kill_date >= '$today' AND msg_date <= '$today' ORDER BY msg_date";
或使用PHP:
$number_of_rows = count($ps->fetchAll());
您还应该学会以正确的方式准备查询
您应该使用 iterator_count
来计算行数,即
$number_of_rows = iterator_count($ps);
我遇到了一个奇怪的问题,一整天都在困扰着我。
我有以下代码:
$today = date("m/d/Y");
$sql = "SELECT * FROM msgs WHERE is_errata = 0 AND kill_date >= '$today' AND msg_date <= '$today' ORDER BY msg_date";
$ps = $pdo->prepare($sql);
if (!$ps) {
echo "PDO::errorInfo():";
print_r($pdo->errorInfo());
}else{
$ps->execute();
$number_of_rows = $ps->rowCount();
当我显示 $number_of_rows 的值时,它总是显示 -1,即使我得到结果也是如此。
还有其他人有这个问题吗?
哦,我使用的数据库不是 MySQL,而是可爱的 MS Access。我怀疑这可能是问题所在。
rowCount()
方法不 return 来自 SELECT
语句的行数。这是常见的错误。
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object. If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
您可以在 documentation 中找到更多详细信息。
因此,要获得行数,您必须使用 sql COUNT(*)
函数编写 SELECT
语句。在你的情况下:
$sql = "SELECT COUNT(*) AS `count` FROM msgs WHERE is_errata = 0 AND kill_date >= '$today' AND msg_date <= '$today' ORDER BY msg_date";
或使用PHP:
$number_of_rows = count($ps->fetchAll());
您还应该学会以正确的方式准备查询
您应该使用 iterator_count
来计算行数,即
$number_of_rows = iterator_count($ps);