php如何实现分页功能
分页功能实现方法
在PHP中实现分页功能通常涉及数据库查询和页面显示的配合。以下是常见的实现方式:
获取总记录数
计算数据库中符合条件的总记录数是分页的基础:
$sql = "SELECT COUNT(*) as total FROM your_table WHERE conditions";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_records = $row['total'];
计算分页参数
根据当前页码和每页显示数量计算分页参数:
$per_page = 10;
$total_pages = ceil($total_records / $per_page);
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $per_page;
查询当前页数据
使用LIMIT子句获取当前页的数据:
$sql = "SELECT * FROM your_table WHERE conditions LIMIT $offset, $per_page";
$result = $conn->query($sql);
生成分页链接
创建分页导航HTML:
echo '<div class="pagination">';
for ($i = 1; $i <= $total_pages; $i++) {
$active = ($i == $current_page) ? 'active' : '';
echo "<a href='?page=$i' class='$active'>$i</a>";
}
echo '</div>';
使用预处理语句(安全版)
为防止SQL注入,建议使用预处理语句:
$stmt = $conn->prepare("SELECT * FROM your_table WHERE conditions LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $per_page);
$stmt->execute();
$result = $stmt->get_result();
分页样式优化
添加CSS样式美化分页导航:
.pagination {
display: inline-block;
}
.pagination a {
color: black;
padding: 8px 16px;
text-decoration: none;
border: 1px solid #ddd;
}
.pagination a.active {
background-color: #4CAF50;
color: white;
border: 1px solid #4CAF50;
}
.pagination a:hover:not(.active) {
background-color: #ddd;
}
高级分页功能
实现更复杂的分页显示,如前后的省略号:
if ($total_pages > 10) {
// 显示部分页码和省略号
$start = max(1, $current_page - 5);
$end = min($total_pages, $current_page + 5);
if ($start > 1) echo "<a href='?page=1'>1</a> ... ";
for ($i = $start; $i <= $end; $i++) {
$active = ($i == $current_page) ? 'active' : '';
echo "<a href='?page=$i' class='$active'>$i</a>";
}
if ($end < $total_pages) echo " ... <a href='?page=$total_pages'>$total_pages</a>";
}
AJAX分页实现
使用jQuery实现无刷新分页:

$(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);
}
});
});






