在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),然后在浏览器中运行该文件,你将看到一个包含分页功能的表格。注意,你需要根据自己的数据库配置修改连接信息。