要通過MySQL的ROW()函數實現數據的分頁顯示,你可以使用以下方法:
SELECT COUNT(*) FROM your_table;
SELECT CEIL(total_records / records_per_page) as total_pages FROM (
SELECT COUNT(*) as total_records FROM your_table
) as subquery;
-- 獲取第2頁的數據,每頁顯示10條記錄
SELECT * FROM your_table
ORDER BY id
LIMIT 10 OFFSET 10;
<?php
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_database';
// 創建連接
$conn = new mysqli($host, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 每頁顯示的記錄數
$records_per_page = 10;
// 獲取請求的頁碼
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
// 計算偏移量
$offset = ($page - 1) * $records_per_page;
// 查詢總記錄數
$sql_total_records = "SELECT COUNT(*) as total_records FROM your_table";
$result_total_records = $conn->query($sql_total_records);
$total_records = $result_total_records->fetch_assoc()['total_records'];
// 計算總頁數
$total_pages = ceil($total_records / $records_per_page);
// 獲取當前頁的數據
$sql_data = "SELECT * FROM your_table ORDER BY id LIMIT $records_per_page OFFSET $offset";
$result_data = $conn->query($sql_data);
// 顯示數據
if ($result_data->num_rows > 0) {
while($row = $result_data->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結果";
}
// 顯示分頁導航
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
// 關閉連接
$conn->close();
?>
這個示例中,我們首先獲取請求的頁碼和每頁顯示的記錄數。然后,我們計算偏移量并使用LIMIT和OFFSET關鍵字來獲取當前頁的數據。最后,我們顯示數據和分頁導航。