有很多相互矛盾的说法。在PHP中使用PDO获得行数的最佳方法是什么?在使用PDO之前,我只是简单地使用了mysql_num_rows。
fetchAll是我不想要的东西,因为我有时可能要处理大型数据集,所以不适合我使用。
你有什么建议吗?
有很多相互矛盾的说法。在PHP中使用PDO获得行数的最佳方法是什么?在使用PDO之前,我只是简单地使用了mysql_num_rows。
fetchAll是我不想要的东西,因为我有时可能要处理大型数据集,所以不适合我使用。
你有什么建议吗?
当前回答
最简单的方法,只有两行,
$sql = $db->query("SELECT COUNT(*) FROM tablename WHERE statement='condition'");
echo $sql->fetchColumn();
其他回答
当它是mysql的问题,如何计算或获得多少行在一个表与PHP PDO我使用这个
// count total number of rows
$query = "SELECT COUNT(*) as total_rows FROM sometable";
$stmt = $con->prepare($query);
// execute query
$stmt->execute();
// get total rows
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];
感谢Mike @ codeofaninja.com
快速一行程序返回第一个条目。这对于非常基本的查询是很好的。
<?php
$count = current($db->query("select count(*) from table")->fetch());
?>
参考
最后我用了这个:
$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>";
}
看看这个链接: http://php.net/manual/en/pdostatement.rowcount.php 不建议在SELECT语句中使用rowCount() !
我尝试$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;