php和mysql实现分页
使用 PHP 和 MySQL 实现分页
分页功能在 Web 开发中非常常见,以下是实现分页的详细步骤:
获取总记录数
需要从数据库中查询总记录数,用于计算总页数。

$sql = "SELECT COUNT(*) AS total FROM your_table";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_records = $row['total'];
设置每页显示的记录数和当前页码
定义每页显示的记录数,并获取当前页码(通常通过 GET 参数传递)。
$records_per_page = 10;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
计算总页数和偏移量
根据总记录数和每页显示的记录数计算总页数,并确定当前页的偏移量。

$total_pages = ceil($total_records / $records_per_page);
$offset = ($current_page - 1) * $records_per_page;
查询当前页的数据
使用 LIMIT 和 OFFSET 从数据库中获取当前页的数据。
$sql = "SELECT * FROM your_table LIMIT $offset, $records_per_page";
$result = $conn->query($sql);
显示分页链接
生成分页导航链接,通常包括上一页、下一页和页码。
if ($current_page > 1) {
echo "<a href='?page=" . ($current_page - 1) . "'>上一页</a>";
}
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'" . ($i == $current_page ? " class='active'" : "") . ">$i</a>";
}
if ($current_page < $total_pages) {
echo "<a href='?page=" . ($current_page + 1) . "'>下一页</a>";
}
完整示例代码
<?php
$conn = new mysqli("localhost", "username", "password", "database");
// 获取总记录数
$sql = "SELECT COUNT(*) AS total FROM your_table";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_records = $row['total'];
// 分页设置
$records_per_page = 10;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$total_pages = ceil($total_records / $records_per_page);
$offset = ($current_page - 1) * $records_per_page;
// 查询当前页数据
$sql = "SELECT * FROM your_table LIMIT $offset, $records_per_page";
$result = $conn->query($sql);
// 显示数据
while ($row = $result->fetch_assoc()) {
echo $row['column_name'] . "<br>";
}
// 显示分页链接
if ($current_page > 1) {
echo "<a href='?page=" . ($current_page - 1) . "'>上一页</a>";
}
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'" . ($i == $current_page ? " class='active'" : "") . ">$i</a>";
}
if ($current_page < $total_pages) {
echo "<a href='?page=" . ($current_page + 1) . "'>下一页</a>";
}
$conn->close();
?>
注意事项
- 确保对 GET 参数进行验证和过滤,防止 SQL 注入。
- 可以根据需求调整分页样式,例如添加 Bootstrap 分页组件。
- 对于大型数据集,考虑使用缓存优化性能。






