php实现的分页
PHP 分页实现方法
基本分页逻辑
分页的核心是通过 SQL 的 LIMIT 子句实现数据分段查询。假设每页显示 10 条记录:
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;
$sql = "SELECT * FROM articles LIMIT {$offset}, {$perPage}";
完整分页类示例
创建一个可复用的分页类:
class Pagination {
private $totalItems;
private $itemsPerPage;
private $currentPage;
public function __construct($totalItems, $itemsPerPage = 10, $currentPage = 1) {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = max(1, $currentPage);
}
public function getOffset() {
return ($this->currentPage - 1) * $this->itemsPerPage;
}
public function getTotalPages() {
return ceil($this->totalItems / $this->itemsPerPage);
}
public function getLinks($url = '?page=') {
$html = '<div class="pagination">';
if ($this->currentPage > 1) {
$html .= '<a href="'.$url.($this->currentPage-1).'">Previous</a>';
}
for ($i = 1; $i <= $this->getTotalPages(); $i++) {
$html .= $i == $this->currentPage
? '<span class="current">'.$i.'</span>'
: '<a href="'.$url.$i.'">'.$i.'</a>';
}
if ($this->currentPage < $this->getTotalPages()) {
$html .= '<a href="'.$url.($this->currentPage+1).'">Next</a>';
}
$html .= '</div>';
return $html;
}
}
数据库查询结合
在实际应用中使用分页类:
// 获取总记录数
$total = $db->query("SELECT COUNT(*) FROM articles")->fetchColumn();
// 创建分页实例
$pagination = new Pagination($total, 10, $_GET['page'] ?? 1);
// 获取当前页数据
$stmt = $db->prepare("SELECT * FROM articles LIMIT :offset, :limit");
$stmt->bindValue(':offset', $pagination->getOffset(), PDO::PARAM_INT);
$stmt->bindValue(':limit', $pagination->itemsPerPage, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll();
// 显示分页链接
echo $pagination->getLinks();
前端样式建议
为分页链接添加基本CSS样式:
.pagination {
margin: 20px 0;
text-align: center;
}
.pagination a, .pagination span {
display: inline-block;
padding: 5px 10px;
margin: 0 2px;
border: 1px solid #ddd;
text-decoration: none;
}
.pagination a:hover {
background: #eee;
}
.pagination .current {
background: #007bff;
color: white;
border-color: #007bff;
}
注意事项
数据库性能优化:对于大型数据集,确保 COUNT(*) 查询有适当索引。InnoDB 引擎下,考虑使用近似计数或缓存计数结果。
安全性:始终验证和过滤输入的页码参数,防止SQL注入和XSS攻击。
URL设计:对于SEO友好的分页,可以考虑使用路径式URL(如 /page/2/)而非查询参数。







