php实现翻页

PHP实现翻页功能
翻页功能是Web开发中常见的需求,可以通过PHP结合数据库查询实现。以下是几种常见的实现方式:
基于LIMIT的简单分页
$perPage = 10; // 每页显示数量
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // 当前页码
$offset = ($page - 1) * $perPage; // 计算偏移量
// 查询数据
$sql = "SELECT * FROM your_table LIMIT $offset, $perPage";
$result = $conn->query($sql);
// 获取总记录数
$total = $conn->query("SELECT COUNT(*) FROM your_table")->fetch_row()[0];
$totalPages = ceil($total / $perPage); // 计算总页数
分页链接生成
// 生成分页链接
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'" . ($i == $page ? " class='active'" : "") . ">$i</a>";
}
使用预处理语句防止SQL注入
$stmt = $conn->prepare("SELECT * FROM your_table LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $perPage);
$stmt->execute();
$result = $stmt->get_result();
更完善的分页类实现
可以创建一个分页类来封装分页逻辑:
class Pagination {
private $total;
private $perPage;
private $currentPage;
public function __construct($total, $perPage, $currentPage) {
$this->total = $total;
$this->perPage = $perPage;
$this->currentPage = $currentPage;
}
public function getOffset() {
return ($this->currentPage - 1) * $this->perPage;
}
public function getTotalPages() {
return ceil($this->total / $this->perPage);
}
public function getLinks($url) {
$links = [];
for ($i = 1; $i <= $this->getTotalPages(); $i++) {
$links[] = [
'url' => "$url?page=$i",
'text' => $i,
'active' => $i == $this->currentPage
];
}
return $links;
}
}
使用AJAX实现无刷新分页
// 前端部分
$(document).on('click', '.pagination a', function(e) {
e.preventDefault();
var page = $(this).attr('href').split('page=')[1];
$.ajax({
url: 'get_data.php',
data: {page: page},
success: function(data) {
$('#content').html(data);
}
});
});
// get_data.php
$page = $_GET['page'] ?? 1;
$offset = ($page - 1) * $perPage;
// 查询并返回数据
注意事项
- 需要验证页码参数,确保是正整数且在有效范围内
- 对于大数据量表,分页查询应考虑性能优化
- 可以使用缓存机制减少数据库查询次数
- 前端可以添加"上一页"和"下一页"按钮提升用户体验
以上方法可以根据具体需求选择或组合使用,实现适合项目的分页功能。







