有很多相互矛盾的说法。在PHP中使用PDO获得行数的最佳方法是什么?在使用PDO之前,我只是简单地使用了mysql_num_rows。

fetchAll是我不想要的东西,因为我有时可能要处理大型数据集,所以不适合我使用。

你有什么建议吗?


当前回答

看看这个链接: http://php.net/manual/en/pdostatement.rowcount.php 不建议在SELECT语句中使用rowCount() !

其他回答

当你在mysql语句中使用COUNT(*)时,比如in

$q = $db->query("SELECT COUNT(*) FROM ...");

你的mysql查询已经在计算结果的数量,为什么在php中再次计数?来获得mysql的结果

$q = $db->query("SELECT COUNT(*) as counted FROM ...");
$nb = $q->fetch(PDO::FETCH_OBJ);
$nb = $nb->counted;

$nb将包含你在mysql语句中计算的整数 写起来有点长,但执行起来很快

编辑: 对不起,错误的帖子,但作为一些例子显示查询与计数在,我建议使用mysql的结果,但如果你不使用计数在sql fetchAll()是有效的,如果你保存在一个变量的结果,你不会失去一行。

$data = $dbh->query("SELECT * FROM ...");
$table = $data->fetchAll(PDO::FETCH_OBJ);

Count ($table)将返回行数,您仍然可以使用像$row = $table[0]或使用foreach后的结果

foreach($table as $row){
  print $row->id;
}

你可以将最好的方法合并到一行或函数中,并自动生成新的查询:

function getRowCount($q){ 
    global $db;
    return $db->query(preg_replace('/SELECT [A-Za-z,]+ FROM /i','SELECT count(*) FROM ',$q))->fetchColumn();
}

$numRows = getRowCount($query);

这太迟了,但我遇到了一个问题,我这样做:

function countAll($table){
   $dbh = dbConnect();
   $sql = "select * from `$table`";

   $stmt = $dbh->prepare($sql);
    try { $stmt->execute();}
    catch(PDOException $e){echo $e->getMessage();}

return $stmt->rowCount();

这真的很简单。:)

下面是PDO类的定制扩展,其中有一个辅助函数,用于检索最后一个查询的“WHERE”条件所包含的行数。

不过,您可能需要添加更多的“处理程序”,这取决于您使用的命令。现在它只适用于使用“FROM”或“UPDATE”的查询。

class PDO_V extends PDO
{
    private $lastQuery = null;

    public function query($query)
    {
        $this->lastQuery = $query;    
        return parent::query($query);
    }
    public function getLastQueryRowCount()
    {
        $lastQuery = $this->lastQuery;
        $commandBeforeTableName = null;
        if (strpos($lastQuery, 'FROM') !== false)
            $commandBeforeTableName = 'FROM';
        if (strpos($lastQuery, 'UPDATE') !== false)
            $commandBeforeTableName = 'UPDATE';

        $after = substr($lastQuery, strpos($lastQuery, $commandBeforeTableName) + (strlen($commandBeforeTableName) + 1));
        $table = substr($after, 0, strpos($after, ' '));

        $wherePart = substr($lastQuery, strpos($lastQuery, 'WHERE'));

        $result = parent::query("SELECT COUNT(*) FROM $table " . $wherePart);
        if ($result == null)
            return 0;
        return $result->fetchColumn();
    }
}

如果你只是想获得行数(而不是数据),即。在预处理语句中使用COUNT(*),那么你所需要做的就是检索结果并读取值:

$sql = "SELECT count(*) FROM `table` WHERE foo = bar";
$statement = $con->prepare($sql); 
$statement->execute(); 
$count = $statement->fetch(PDO::FETCH_NUM); // Return array indexed by column number
return reset($count); // Resets array cursor and returns first value (the count)

实际上,检索所有行(数据)来执行简单的计数是一种资源浪费。如果结果集很大,您的服务器可能会因此阻塞。