MySQL LIMIT offset, count 是分頁查詢的標準方式。本文提供一個完整的 PHP 分頁類,包含記錄讀取、頁碼計算、導航生成,適合中小型項目直接使用。
($page - 1) * $pageSizeceil($totalRecords / $pageSize)SELECT * FROM table ORDER BY col LIMIT $offset, $pageSize<?php
$pageSize = 20;
$page = isset($_GET['startpage']) ? intval($_GET['startpage']) : 1;
$offset = ($page - 1) * $pageSize;
// 連接數據庫
$conn = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('book', $conn);
// 獲取總記錄數
$totalSql = "SELECT COUNT(*) AS total FROM main";
$totalRes = mysql_query($totalSql, $conn);
$totalRow = mysql_fetch_assoc($totalRes);
$totalRecords = $totalRow['total'];
$totalPages = ceil($totalRecords / $pageSize);
// 分頁查詢
$sql = "SELECT * FROM main ORDER BY sm LIMIT $offset, $pageSize";
$res = mysql_query($sql, $conn);
// 輸出表格
echo "<table border=1><tr><th>序號</th><th>書號</th><th>書名</th><th>出版社</th><th>定價</th></tr>";
$i = 1;
while ($row = mysql_fetch_assoc($res)) {
echo "<tr><td>$i</td><td>{$row['bzsh']}</td><td>{$row['sm']}</td><td>{$row['cbs']}</td><td>{$row['dj']}</td></tr>";
$i++;
}
echo "</table>";
// 生成導航
$prev = $page - 1;
$next = $page + 1;
echo "<hr>";
if ($page == 1) {
echo "首頁 前頁 ";
if ($totalPages > 1) echo "<a href='?startpage=$next'>下頁</a> <a href='?startpage=$totalPages'>尾頁</a>";
else echo "下頁 尾頁 ";
} elseif ($page == $totalPages) {
echo "<a href='?startpage=1'>首頁</a> <a href='?startpage=$prev'>前頁</a> 下頁 尾頁 ";
} else {
echo "<a href='?startpage=1'>首頁</a> <a href='?startpage=$prev'>前頁</a> ";
echo "<a href='?startpage=$next'>下頁</a> <a href='?startpage=$totalPages'>尾頁</a> ";
}
echo " 共 $totalPages 頁 第 $page 頁";
mysql_close($conn);
?>
mysqli 或 PDO 替代已棄用的 mysql_* 函數WHERE id > $lastId ORDER BY id LIMIT 20EXPLAIN rows)