如何使用 PHP 計算 MySQL 表中的行數
為了取得 MySQL 表中的總行數,PHP 提供了幾種方法。讓我們深入研究最常見的方法。
使用關聯數組
$sql = "SELECT COUNT(*) FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_assoc($result)['COUNT(*)']; echo $count;
使用列別名
$sql = "SELECT COUNT(*) as cnt FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_assoc($result)['cnt']; echo $count;
使用數字數組
$sql = "SELECT COUNT(*) FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_row($result)[0]; echo $count;
PHP 8.1 簡化
$sql = "SELECT COUNT(*) FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_column($result); echo $count;
物件導向的方法
$sql = "SELECT COUNT(*) FROM news"; $count = $con->query($sql)->fetch_row()[0]; echo $count;
$sql = "SELECT COUNT(*) FROM news WHERE category=?"; $stmt = $con->prepare($sql); $stmt->bind_param('s', $category); $stmt->execute(); $count = $stmt->get_result()->fetch_row()[0]; echo $count;
以上是如何使用 PHP 有效率地計算 MySQL 表中的行數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!