分頁本質是 LIMIT offset, count。關鍵參數:
$pageSize:每頁條數 (如 10、20)$currentPage:當前頁碼 (從 1 開始,GET 參數獲取)$totalRecords:總記錄數 (SELECT COUNT(*))$totalPages = ceil($totalRecords / $pageSize)$offset = ($currentPage - 1) * $pageSize<?php
// 配置
$pageSize = 15;
$currentPage = max(1, (int)($_GET['page'] ?? 1));
// 1. 獲取總記錄數 (單獨查詢,可快取)
$stmt = $pdo->query('SELECT COUNT(*) FROM articles WHERE status = 1');
$totalRecords = $stmt->fetchColumn();
$totalPages = (int)ceil($totalRecords / $pageSize);
// 2. 修正頁碼範圍
$currentPage = min($currentPage, max(1, $totalPages));
// 3. 查詢當前頁數據
$offset = ($currentPage - 1) * $pageSize;
$stmt = $pdo->prepare('SELECT id, title, created_at FROM articles WHERE status = 1 ORDER BY created_at DESC LIMIT :offset, :limit');
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll();
// 4. 生成頁碼導航 HTML (核心邏輯)
function render_pagination(int $currentPage, int $totalPages, string $baseUrl, int $displayCount = 5): string {
if ($totalPages <= 1) return '';
$html = '';
return $html;
}
// 使用
$baseUrl = $_SERVER['PHP_SELF']; // 或指定路由
echo render_pagination($currentPage, $totalPages, $baseUrl, 7);
?>
避免 OFFSET 深分頁掃描大量行。利用唯一、有序列 (如 id、created_at) 記住上一頁最後一條記錄的值。
// 第一頁
SELECT * FROM articles WHERE status=1 ORDER BY id DESC LIMIT 15;
// 後續頁 (假設上一頁最小 id = 10050)
SELECT * FROM articles WHERE status=1 AND id < 10050 ORDER BY id DESC LIMIT 15;
// 無 OFFSET,索引命中極快,無論翻多深效能恆定
缺點:不能隨意跳頁、不支援按非唯一欄位排序 (需組合唯一鍵)。
COUNT(*) 在大表 (InnoDB) 較慢。將總數存入 Redis 快取,定期 (如每分鐘) 或異步更新。允許總頁數略有誤差 (用戶無感)。
移動端體驗更好。後端返回 {data: [], nextCursor: 10050, hasMore: true},前端追加渲染。
$articles = Article::paginate(15); 自動處理查詢、鏈接、視圖 ({{ $articles->links() }})。支援 simplePaginate (無總數)、cursorPaginate (游標)。KnpPaginatorBundle 或 Doctrine Paginator。Db::name('articles')->paginate(15);。基礎分頁掌握 LIMIT offset, size 與頁碼導航生成邏輯。大數據場景**必須**遷移至**游標分頁**。善用快取總數、框架內建組件,避免重複造輪子。前端體驗上,PC 端傳統分頁、移動端無限滾動並存。