MySQL 的 LIMIT offset, count 是分頁的關鍵:
offset:起始行號(從 0 開始)count:每頁顯示記錄數SELECT * FROM table ORDER BY id DESC LIMIT $start, $limit
適用於記錄較少、不需頁碼導航的場景。
$limit = 20 條。$start 初始為 0,向後翻頁 $start += $limit,向前 $start -= $limit。$num_max 控制「下一頁」顯示條件。<?php
$limit = 20; // 每頁顯示數量
$start = isset($_GET['start']) ? (int)$_GET['start'] : 0; // 當前起始位置
$conn = mysqli_connect("localhost", "user", "pass", "database");
// 總記錄數
$totalRes = mysqli_query($conn, "SELECT * FROM `table`");
$num_max = mysqli_num_rows($totalRes);
// 當前頁數據
$res = mysqli_query($conn, "SELECT * FROM `table` ORDER BY id DESC LIMIT $start, $limit");
$num = mysqli_num_rows($res);
echo "<table><tr><td>分頁演示</td></tr>";
if ($num) {
while ($row = mysqli_fetch_assoc($res)) {
echo "<tr><td>{$row['val']}</td><td>{$row['val1']}</td></tr>";
}
}
// 上一頁
$prev = $start - $limit;
if ($prev >= 0) {
echo "<tr><td><a href='page.php?start=$prev'>上一頁</a></td></tr>";
}
// 下一頁
$next = $start + $limit;
if ($next < $num_max) {
echo "<tr><td><a href='page.php?start=$next'>下一頁</a></td></tr>";
}
echo "</table>";
?>
注意:示例使用 mysqli 替代已棄用的 mysql 擴展,並對輸入做 (int) 強制類型轉換防注入。
當記錄很多時,需顯示頁碼(如 1 2 3 ... 10),邏輯較複雜:
$totalPages = ceil($num_max / $limit)。$currentPage = floor($start / $limit) + 1。此處不展開完整代碼,核心思路是根據 $currentPage 和 $totalPages 動態構建導航 HTML。成熟專案建議封裝為分頁類或使用框架內置分頁組件。
mysqli 或 PDO 替代舊 mysql 擴展。OFFSET 深分頁性能下降,可改用「游標分頁」(WHERE id > last_id LIMIT n)。