一个不依赖框架的分页类
传入总条数、每页条数和当前页,输出 SQL 的 LIMIT 片段和页码 HTML。处理了越界页和只剩一页的情况。
更新于 2026-11-1857 行代码
完整代码
PHP
<?php
class Pager
{
public int $total;
public int $perPage;
public int $page;
public int $pages;
public function __construct(int $total, int $perPage = 20, int $page = 1)
{
$this->total = max(0, $total);
$this->perPage = max(1, $perPage);
$this->pages = (int)ceil($this->total / $this->perPage) ?: 1;
$this->page = min(max(1, $page), $this->pages);
}
public function offset(): int
{
return ($this->page - 1) * $this->perPage;
}
public function limitSql(): string
{
return ' LIMIT ' . $this->offset() . ', ' . $this->perPage;
}
/** 生成页码,$base 是带 %d 的地址模板 */
public function html(string $base, int $span = 2): string
{
if ($this->pages <= 1) {
return '';
}
$out = '<nav class="pager">';
$start = max(1, $this->page - $span);
$end = min($this->pages, $this->page + $span);
if ($this->page > 1) {
$out .= sprintf('<a href="' . $base . '">上一页</a>', $this->page - 1);
}
if ($start > 1) {
$out .= sprintf('<a href="' . $base . '">1</a>', 1);
if ($start > 2) $out .= '<span>…</span>';
}
for ($i = $start; $i <= $end; $i++) {
$cls = $i === $this->page ? ' class="on"' : '';
$out .= sprintf('<a href="' . $base . '"' . $cls . '>' . $i . '</a>', $i);
}
if ($end < $this->pages) {
if ($end < $this->pages - 1) $out .= '<span>…</span>';
$out .= sprintf('<a href="' . $base . '">' . $this->pages . '</a>', $this->pages);
}
if ($this->page < $this->pages) {
$out .= sprintf('<a href="' . $base . '">下一页</a>', $this->page + 1);
}
return $out . '</nav>';
}
}
怎么用
- 把类文件放到 src/Pager.php,用 require 或自动加载引入。
- 先 count 出总数:$total = (int)$pdo->query('SELECT COUNT(*) FROM articles')->fetchColumn();
- new Pager($total, 20, (int)($_GET['page'] ?? 1)),用 $pager->limitSql() 拼到查询后面。
- 输出页码:echo $pager->html('/articles/?page=%d');
注意
- LIMIT 后拼的是已经转成整数的值,不存在注入风险;页码本身也要 (int) 转换。
- 总数很大时 COUNT(*) 会慢,可以缓存总数或改成「只判断有没有下一页」。
- 深翻页仍然慢,超过 50 页建议改用游标分页(WHERE id < ?)。