分頁是 Web 應用核心功能。本文從基礎 LIMIT offset, rows 切入,推導偏移計算,提供完整 PHP 分頁類封裝,含導航生成、下拉跳轉、URL 參數保持。
-- 第 1 頁 (每頁 10 筆)
SELECT * FROM articles LIMIT 0, 10;
-- 第 n 頁
SELECT * FROM articles LIMIT (n-1)*10, 10;
-- 參數化 (PHP)
$offset = ($page - 1) * $pageSize;
$sql = "SELECT * FROM articles LIMIT $offset, $pageSize";
total = $total;
$this->pageSize = $pageSize;
$this->url = $url ?: $_SERVER['REQUEST_URI'];
$this->init();
}
private function init() {
if (!$this->page) $this->page = 1;
// 清理 URL 中舊的 page 參數
$parsed = parse_url($this->url);
$query = $parsed['query'] ?? '';
$query = preg_replace('/(^|&)page=\d+/', '', $query);
$this->url = str_replace($parsed['query'], $query, $this->url);
$this->url .= (strpos($this->url, '?') ? '&' : '?') . 'page=';
$lastPage = ceil($this->total / $this->pageSize);
$this->page = min($lastPage, max(1, $this->page));
$this->offset = ($this->page - 1) * $this->pageSize;
$this->buildNav($lastPage);
}
private function buildNav($lastPage) {
if ($lastPage <= 1) return;
$this->nav = "顯示第 " . ($this->offset + 1) . "-" .
min($this->offset + $this->pageSize, $this->total) . " 條,共 $this->total 條
";
// 首頁/上一頁
$this->nav .= " 首頁 ";
$this->nav .= ($this->page > 1)
? " 上一頁 "
: " 上一頁 ";
// 頁碼區間 (當前頁前後各 2)
$start = max(1, $this->page - 2);
$end = min($lastPage, $this->page + 2);
for ($i = $start; $i <= $end; $i++) {
$this->nav .= ($i == $this->page)
? " $i "
: " $i ";
}
// 下一頁/尾頁
$this->nav .= ($this->page < $lastPage)
? " 下一頁 "
: " 下一頁 ";
$this->nav .= " 尾頁 ";
// 下拉跳轉
$this->nav .= " 到第 頁,共 $lastPage 頁";
}
public function getLimit() {
return "LIMIT {$this->offset}, {$this->pageSize}";
}
public function getOffset() {
return $this->offset;
}
}
query("SELECT COUNT(*) FROM articles")->fetch_row()[0];
// 2. 實例化分頁器
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$pager = new Pager($total, 10);
$pager->page = $page;
// 3. 查詢當前頁資料
$sql = "SELECT id, title, created_at FROM articles ORDER BY created_at DESC " . $pager->getLimit();
$result = $mysqli->query($sql);
// 4. 輸出資料
while ($row = $result->fetch_assoc()) {
echo "{$row['title']} {$row['created_at']}";
}
// 5. 輸出分頁導航
echo $pager->nav;
?>
-- ❌ 慢:大偏移 LIMIT 100000, 20
-- ✅ 快:延遲關聯
SELECT a.* FROM articles a
JOIN (SELECT id FROM articles ORDER BY created_at DESC LIMIT 100000, 20) b
USING (id)
ORDER BY a.created_at DESC;
-- ✅ 最快:游標式 (需前端配合 last_id)
SELECT * FROM articles WHERE id < $last_id ORDER BY id DESC LIMIT 20;
parse_url + parse_str 解析重組lastId,API 支援 ?last_id=xxx&limit=20rel="next/prev" 或 Canonical