萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 分頁查詢完整實戰:LIMIT 偏移計算、分頁導航、完整 PHP 類封裝

MySQL 分頁查詢工程化實踐:從基礎 LIMIT 到完整分頁元件

分頁是 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";

完整 PHP 分頁類 (可直接生產使用)


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;

URL 參數保持最佳實踐

  • 使用 parse_url + parse_str 解析重組
  • 保留搜尋、篩選、排序等參數
  • 避免手動字串拼接導致參數丟失或重複

前端整合建議

  • 導航區塊獨立 Partial/View Component
  • AJAX 分頁:回傳 JSON {data: [], pagination: {page, total, pageSize, lastPage}}
  • 無限滾動:前端維護 lastId,API 支援 ?last_id=xxx&limit=20
  • SEO:首頁渲染完整 HTML,分頁頁面 rel="next/prev" 或 Canonical
copyright © 萬盛學電腦網 all rights reserved