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

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

你有什么建议吗?


当前回答

要在查询中使用变量,必须使用bindValue()或bindParam()。并且不要将变量与"连在一起。$variable。”

$statement = "SELECT count(account_id) FROM account
                  WHERE email = ? AND is_email_confirmed;";
$preparedStatement = $this->postgreSqlHandler->prepare($statement);
$preparedStatement->bindValue(1, $account->getEmail());
$preparedStatement->execute();
$numberRows= $preparedStatement->fetchColumn();

GL

其他回答

快速一行程序返回第一个条目。这对于非常基本的查询是很好的。

<?php
$count = current($db->query("select count(*) from table")->fetch());
?>

参考

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

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

$numRows = getRowCount($query);

我尝试$count = $stmt->rowCount();在Oracle 11.2中,它没有工作。 我决定使用一个for循环,如下所示。

   $count =  "";
    $stmt =  $conn->prepare($sql);
    $stmt->execute();
   echo "<table border='1'>\n";
   while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
        $count++;
        echo "<tr>\n";
    foreach ($row as $item) {
    echo "<td class='td2'>".($item !== null ? htmlentities($item, ENT_QUOTES):"&nbsp;")."</td>\n";
        } //foreach ends
        }// while ends
        echo "</table>\n";
       //echo " no of rows : ". oci_num_rows($stmt);
       //equivalent in pdo::prepare statement
       echo "no.of rows :".$count;

最简单的方法,只有两行,

$sql = $db->query("SELECT COUNT(*) FROM tablename WHERE statement='condition'");
echo $sql->fetchColumn();

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

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();

这真的很简单。:)