php分页实现
PHP分页实现方法
基础分页逻辑
使用LIMIT和OFFSET实现数据库分页查询:
$perPage = 10; // 每页显示数量
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$sql = "SELECT * FROM articles LIMIT $offset, $perPage";
$result = $conn->query($sql);
计算总页数
获取总记录数并计算总页数:
$totalQuery = "SELECT COUNT(*) as total FROM articles";
$totalResult = $conn->query($totalQuery);
$totalRows = $totalResult->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $perPage);
生成分页链接
创建分页导航HTML:
echo '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
$active = $i == $page ? 'active' : '';
echo "<a href='?page=$i' class='$active'>$i</a>";
}
echo '</div>';
使用PDO预处理语句
更安全的分页查询实现:
$stmt = $conn->prepare("SELECT * FROM articles LIMIT :offset, :perPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
Bootstrap分页样式
使用Bootstrap美化分页导航:
echo '<nav aria-label="Page navigation">
<ul class="pagination">';
if ($page > 1) {
echo '<li class="page-item"><a class="page-link" href="?page='.($page-1).'">Previous</a></li>';
}
for ($i = 1; $i <= $totalPages; $i++) {
$active = $i == $page ? ' active' : '';
echo '<li class="page-item'.$active.'"><a class="page-link" href="?page='.$i.'">'.$i.'</a></li>';
}
if ($page < $totalPages) {
echo '<li class="page-item"><a class="page-link" href="?page='.($page+1).'">Next</a></li>';
}
echo '</ul></nav>';
分页类封装
创建可重用的分页类:
class Paginator {
private $totalItems;
private $itemsPerPage;
private $currentPage;
public function __construct($totalItems, $itemsPerPage, $currentPage) {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
}
public function getTotalPages() {
return ceil($this->totalItems / $this->itemsPerPage);
}
public function getOffset() {
return ($this->currentPage - 1) * $this->itemsPerPage;
}
}
AJAX分页实现
使用jQuery实现无刷新分页:
$(document).on('click', '.pagination a', function(e) {
e.preventDefault();
var page = $(this).attr('href').split('page=')[1];
$.ajax({
url: 'load_data.php',
type: 'GET',
data: {page: page},
success: function(data) {
$('#content').html(data);
}
});
});
这些方法涵盖了从基础到进阶的PHP分页实现,可以根据项目需求选择适合的方案。






