所有分頁邏輯圍繞 SELECT * FROM goods LIMIT offset, count 展開:
count:每頁筆數(固定)offset:跳過筆數 = (當前頁 - 1) * 每頁筆數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 "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);
}
}
$cfg_dbhost = 'localhost'; $cfg_dbname = 'test'; $cfg_dbuser = 'root'; $cfg_dbpw = '123456';

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