下面是一個簡單的PHP分頁代碼示例:
<?php
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接是否成功
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 獲取當前頁數和每頁顯示的記錄數
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$records_per_page = 10;
$offset = ($page - 1) * $records_per_page;
// 查詢數據庫中的記錄
$sql = "SELECT * FROM table_name LIMIT $offset, $records_per_page";
$result = $conn->query($sql);
// 顯示記錄
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結果";
}
// 計算總記錄數和總頁數
$total_records = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM table_name"));
$total_pages = ceil($total_records / $records_per_page);
// 顯示分頁鏈接
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=$i'>$i</a> ";
}
// 關閉數據庫連接
$conn->close();
?>
以上代碼是一個簡單的PHP分頁示例,通過使用LIMIT語句和計算總記錄數來實現分頁功能。您可以根據自己的需求和數據庫結構進行調整和修改。