0

我正在尝试使用 PDO(在 MySql 表上)计算项目数。我在某处读到 rowCount 在 MySql 上不起作用。这个对吗?

到目前为止,我肯定无法让它工作,因为我不断得到 count=0。

谁能给我一个想法,这样我就可以避免每次都回到数据库?我有多个与此类似的查询:

    $items = $con -> prepare("SELECT * FROM item_descr ORDER BY $sortBy DESC");
    $count = $items -> rowCount();
    $items -> execute();
while($info = $items->fetch(PDO::FETCH_ASSOC)) { ... }

我想尽量避免额外的查询SELECT COUNT (*)

谢谢!

4

7 回答 7

7

您需要 execute查询。只有这样数据库才能完成它的工作,只有这样你才能获得找到的结果的计数。

于 2012-08-23T15:24:57.693 回答
2

正如@deceze 所指出的,

$items = $con -> prepare("SELECT * FROM item_descr ORDER BY $sortBy DESC");
$items -> execute();
$count = $items -> rowCount();
while($info = $items->fetch(PDO::FETCH_ASSOC)) { ... }
于 2012-08-23T15:27:50.460 回答
1

仅此而已,请参阅 PHP 文档:

http://www.php.net/manual/en/pdostatement.rowcount.php

特别:

对于大多数数据库,PDOStatement::rowCount() 不返回受 SELECT 语句影响的行数。相反,使用 PDO::query() 发出 SELECT COUNT(*) 语句,其谓词与预期的 SELECT 语句相同,然后使用 PDOStatement::fetchColumn() 检索将返回的行数。然后,您的应用程序可以执行正确的操作。

以及来自所述页面的示例:

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories > 100";
       foreach ($conn->query($sql) as $row) {
           print "Name: " .  $row['NAME'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>
于 2012-10-30T20:30:05.350 回答
1

rowCount仅在execute. rowCount我在 MySQL中从来没有遇到过问题。

使用rowCount很好,但如果您要遍历结果,也可以使用自己的计数器变量。

于 2012-08-23T15:25:26.040 回答
0

You can simplify your code so much if you are using PDO, such as:

$items = $conn->query("SELECT * FROM item_descr ORDER BY $sortBy DESC")->fetchAll(PDO::FETCH_ASSOC);

if(count($items))
{
    // You can count the array to see how many records you got and you can iterate trough it using foreach / for loops 
}
else 
{
    // 0 records returned
}

There is no need for prepared statements in this particular case or checking whether you got any rows back using rowCount. It is true that rowCount CAN fail even with MySQL, it all depends whether you are using unbuffered queries or not.

于 2012-08-23T15:32:26.987 回答
-1

这对我有用:

$my_query = $db->query('SELECT COUNT(*) AS Count FROM the_table');
$c = $my_query->fetch(PDO::FETCH_OBJ);

return $c->Count;
于 2014-01-31T07:44:15.220 回答
-1

PDOStatement::rowCount() 返回仅受 DELETE、INSERT 或 UPDATE 语句影响的行数。

对于大多数数据库,PDOStatement::rowCount() 不返回受 SELECT 语句影响的行数。相反,使用 PDO::query() 发出 SELECT COUNT(*) 语句,其谓词与预期的 SELECT 语句相同,然后使用 PDOStatement::fetchColumn() 检索将返回的行数。然后,您的应用程序可以执行正确的操作。

于 2014-06-16T07:18:09.560 回答