php实现文章分页
PHP实现文章分页的方法
数据库分页查询
使用SQL的LIMIT子句实现分页查询。假设每页显示10条数据,当前页码为$page:
$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);
计算总页数
查询总记录数并计算总页数:
$totalSql = "SELECT COUNT(*) as total FROM articles";
$totalResult = $conn->query($totalSql);
$totalRows = $totalResult->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $perPage);
生成分页链接
创建分页导航链接:

echo '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
echo '<a href="?page=' . $i . '">' . $i . '</a> ';
}
echo '</div>';
使用PDO预处理语句
更安全的方式是使用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();
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
前端显示优化
添加当前页样式和上一页/下一页按钮:

echo '<div class="pagination">';
if ($page > 1) {
echo '<a href="?page=' . ($page - 1) . '">上一页</a> ';
}
for ($i = 1; $i <= $totalPages; $i++) {
$active = ($i == $page) ? ' class="active"' : '';
echo '<a href="?page=' . $i . '"' . $active . '>' . $i . '</a> ';
}
if ($page < $totalPages) {
echo '<a href="?page=' . ($page + 1) . '">下一页</a>';
}
echo '</div>';
AJAX分页实现
使用jQuery实现无刷新分页:
$(document).on('click', '.pagination a', function(e) {
e.preventDefault();
var page = $(this).attr('href').split('page=')[1];
$.ajax({
url: 'get_articles.php',
type: 'GET',
data: {page: page},
success: function(data) {
$('#articles-container').html(data);
}
});
});
性能优化建议
对于大型数据集,考虑使用缓存分页结果。添加ORDER BY子句确保分页顺序一致:
$sql = "SELECT * FROM articles ORDER BY created_at DESC LIMIT $offset, $perPage";






