php 分页怎么实现
PHP 分页实现方法
数据库查询与分页逻辑
分页的核心是通过 SQL 的 LIMIT 子句实现数据分段查询。假设每页显示 10 条数据,当前页码为 $page:
$itemsPerPage = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $itemsPerPage;
$sql = "SELECT * FROM articles LIMIT $offset, $itemsPerPage";
$result = $pdo->query($sql);
计算总页数
需要先查询总记录数以确定分页数量:

$totalItems = $pdo->query("SELECT COUNT(*) FROM articles")->fetchColumn();
$totalPages = ceil($totalItems / $itemsPerPage);
生成分页导航
输出分页链接时需处理边界情况(如第一页/最后一页):
echo '<div class="pagination">';
if ($page > 1) {
echo '<a href="?page='.($page - 1).'">上一页</a>';
}
for ($i = 1; $i <= $totalPages; $i++) {
echo '<a href="?page='.$i.'"'.($i == $page ? ' class="active"' : '').'>'.$i.'</a>';
}
if ($page < $totalPages) {
echo '<a href="?page='.($page + 1).'">下一页</a>';
}
echo '</div>';
使用预处理语句(安全增强)
为防止 SQL 注入,建议使用预处理语句:

$stmt = $pdo->prepare("SELECT * FROM articles LIMIT :offset, :limit");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $itemsPerPage, PDO::PARAM_INT);
$stmt->execute();
分页样式优化
通过 CSS 美化分页导航,例如:
.pagination a {
padding: 8px 16px;
border: 1px solid #ddd;
margin: 0 4px;
}
.pagination a.active {
background-color: #4CAF50;
color: white;
}
扩展方案:封装分页类
对于复杂项目,可封装可复用的分页类:
class Paginator {
private $totalItems;
private $itemsPerPage;
public function __construct($totalItems, $itemsPerPage) {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
}
public function getTotalPages() {
return ceil($this->totalItems / $this->itemsPerPage);
}
public function getOffset($currentPage) {
return ($currentPage - 1) * $this->itemsPerPage;
}
}






