有很多相互矛盾的说法。在PHP中使用PDO获得行数的最佳方法是什么?在使用PDO之前,我只是简单地使用了mysql_num_rows。
fetchAll是我不想要的东西,因为我有时可能要处理大型数据集,所以不适合我使用。
你有什么建议吗?
有很多相互矛盾的说法。在PHP中使用PDO获得行数的最佳方法是什么?在使用PDO之前,我只是简单地使用了mysql_num_rows。
fetchAll是我不想要的东西,因为我有时可能要处理大型数据集,所以不适合我使用。
你有什么建议吗?
当前回答
看看这个链接: http://php.net/manual/en/pdostatement.rowcount.php 不建议在SELECT语句中使用rowCount() !
其他回答
看看这个链接: http://php.net/manual/en/pdostatement.rowcount.php 不建议在SELECT语句中使用rowCount() !
这太迟了,但我遇到了一个问题,我这样做:
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();
这真的很简单。:)
你可以将最好的方法合并到一行或函数中,并自动生成新的查询:
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):" ")."</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;
最后我用了这个:
$result = $db->query($query)->fetchAll();
if (count($result) > 0) {
foreach ($result as $row) {
echo $row['blah'] . '<br />';
}
} else {
echo "<p>Nothing matched your query.</p>";
}