在PHP中,實現table分頁功能需要以下幾個步驟:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 查詢數據
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
?>
<?php
$records_per_page = 10;
?>
<?php
// 計算總頁數
$total_pages = ceil($result->num_rows / $records_per_page);
// 獲取當前頁
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
// 防止頁碼超出范圍
if ($page < 1) {
$page = 1;
} elseif ($page > $total_pages) {
$page = $total_pages;
}
?>
LIMIT
子句限制查詢結果,只返回當前頁的記錄。<?php
$start_from = ($page - 1) * $records_per_page;
$sql = "SELECT id, name, email FROM users LIMIT $start_from, $records_per_page";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>分頁功能</title>
</head>
<body><table border="1">
<tr>
<th>ID</th>
<th>姓名</th>
<th>郵箱</th>
</tr>
<?php while($row = $result->fetch_assoc()): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
<?php endwhile; ?>
</table>
<nav>
<ul>
<li><a href="?page=1">首頁</a></li>
<li><a href="?page=<?php echo $page - 1; ?>">上一頁</a></li>
<li><a href="?page=<?php echo $page + 1; ?>">下一頁</a></li>
<li><a href="?page=<?php echo $total_pages; ?>">尾頁</a></li>
</ul>
</nav>
</body>
</html>
<?php
$conn->close();
?>
將以上代碼保存為一個PHP文件(例如:pagination.php),然后在瀏覽器中運行該文件,你將看到一個包含分頁功能的表格。注意,你需要根據自己的數據庫配置修改連接信息。