首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 分頁核心原理與最簡實作完整教學

     編輯:PHP 相關知識

分頁核心:SQL LIMIT 子句

所有分頁邏輯圍繞 SELECT * FROM goods LIMIT offset, count 展開:

  • count:每頁筆數(固定)
  • offset:跳過筆數 = (當前頁 - 1) * 每頁筆數

完整實作程式碼

index.php - 主邏輯

include 'conn.php';
$conn = new conn();

// 取得總筆數
$total = $conn->getOne('SELECT COUNT(*) AS total FROM goods');
$total = $total['total'];

$num = 6;                    // 每頁 6 筆
$totalPage = ceil($total / $num);  // 總頁數

// 當前頁碼驗證
$thisPage = (isset($_GET['page']) && $_GET['page'] <= $totalPage) ? (int)$_GET['page'] : 1;

// 計算 offset 並查詢
$offset = ($thisPage - 1) * $num;
$sql = "SELECT goods_id, goods_name, shop_price FROM goods ORDER BY goods_id LIMIT $offset, $num";
$data = $conn->getAll($sql);

// 顯示資料
foreach ($data as $v) {
    echo "
  • {$v['goods_id']}、{$v['goods_name']}---¥{$v['shop_price']}
  • "; } // 顯示頁碼連結 for ($i = 1; $i <= $totalPage; $i++) { echo '' . $i . ' '; }

    conn.php - PDO 資料庫封裝

    class conn {
        private $pdo;
    
        public function __construct() {
            include_once('config.php');
            try {
                $this->pdo = new PDO("mysql:host=$cfg_dbhost;dbname=$cfg_dbname", $cfg_dbuser, $cfg_dbpw);
                $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->pdo->exec('SET NAMES utf8');
            } catch (PDOException $e) {
                die('資料庫連線失敗: ' . $e->getMessage());
            }
        }
    
        public function getOne($sql) {
            return $this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
        }
    
        public function getAll($sql) {
            return $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        }
    }

    config.php - 設定檔

    $cfg_dbhost = 'localhost';
    $cfg_dbname = 'test';
    $cfg_dbuser = 'root';
    $cfg_dbpw = '123456';

    執行效果

    分頁示意圖

    進階優化方向

    • 加入「首頁、上一頁、下一頁、尾頁」導航
    • 頁碼過多時折疊顯示(如 1 ... 5 6 7 ... 20)
    • URL 重寫美化(/page/3 取代 ?page=3)
    • AJAX 無刷新分頁
    • 資料庫索引優化大量資料查詢效能

    總結

    掌握 LIMIT offset, count 與頁碼換算公式,即掌握分頁本質。此範例為教學用途,實務專案建議使用成熟分頁庫(如 Laravel Paginator、Yii2 Pagination)。

    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved