php 实现翻页
实现翻页的基本方法
在PHP中实现翻页功能通常需要结合数据库查询和前端展示。以下是一个常见的实现方式:
计算总页数
$itemsPerPage = 10;
$totalItems = // 从数据库获取总记录数
$totalPages = ceil($totalItems / $itemsPerPage);
获取当前页码
$currentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($currentPage - 1) * $itemsPerPage;
数据库查询
$query = "SELECT * FROM your_table LIMIT $offset, $itemsPerPage";
// 执行查询并获取结果
前端分页链接生成
基本分页链接
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
改进的分页导航

$range = 2; // 显示当前页前后多少页
$start = max(1, $currentPage - $range);
$end = min($totalPages, $currentPage + $range);
if ($start > 1) echo "<a href='?page=1'>1</a> ... ";
for ($i = $start; $i <= $end; $i++) {
$active = ($i == $currentPage) ? " class='active'" : "";
echo "<a href='?page=$i'$active>$i</a> ";
}
if ($end < $totalPages) echo "... <a href='?page=$totalPages'>$totalPages</a>";
使用预处理语句防止SQL注入
PDO方式
$stmt = $pdo->prepare("SELECT * FROM your_table LIMIT :offset, :limit");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $itemsPerPage, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll();
分页类封装
可以创建一个分页类来复用代码:
class Paginator {
private $totalItems;
private $itemsPerPage;
private $currentPage;
public function __construct($totalItems, $itemsPerPage, $currentPage) {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
}
public function getOffset() {
return ($this->currentPage - 1) * $this->itemsPerPage;
}
public function getTotalPages() {
return ceil($this->totalItems / $this->itemsPerPage);
}
// 其他分页相关方法...
}
使用框架的分页功能
许多PHP框架内置了分页功能:

Laravel示例
$items = DB::table('your_table')->paginate(15);
// 视图中显示分页链接
{{ $items->links() }}
ThinkPHP示例
$list = Db::name('your_table')->paginate(10);
// 模板中显示分页
{$list->render()}
性能优化建议
对于大数据表,避免使用COUNT(*)计算总数,可以考虑缓存总记录数或使用近似值。
在MySQL中可以使用SQL_CALC_FOUND_ROWS和FOUND_ROWS()组合:
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM your_table LIMIT $offset, $itemsPerPage";
// 执行查询后
$totalItems = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();






