php实现的分页
PHP 分页实现方法
分页是 Web 开发中常见的功能,PHP 可以通过多种方式实现分页。以下是几种常见的实现方法:
基础分页实现
使用 MySQL 的 LIMIT 子句实现基本分页功能:
// 数据库连接
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 当前页码
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10; // 每页显示数量
$offset = ($page - 1) * $perPage;
// 查询数据
$stmt = $db->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();
// 获取总记录数
$total = $db->query("SELECT COUNT(*) FROM articles")->fetchColumn();
$totalPages = ceil($total / $perPage);
分页链接生成
生成分页导航链接:
// 分页导航
$pagination = '';
for ($i = 1; $i <= $totalPages; $i++) {
$active = ($i == $page) ? 'active' : '';
$pagination .= "<a href='?page=$i' class='$active'>$i</a> ";
}
使用 Bootstrap 样式
结合 Bootstrap 的分页样式:
$pagination = '<nav><ul class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
$active = ($i == $page) ? 'active' : '';
$pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
}
$pagination .= '</ul></nav>';
高级分页类
创建一个可重用的分页类:

class Pagination {
private $totalItems;
private $itemsPerPage;
private $currentPage;
public function __construct($totalItems, $itemsPerPage, $currentPage) {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
}
public function getTotalPages() {
return ceil($this->totalItems / $this->itemsPerPage);
}
public function getOffset() {
return ($this->currentPage - 1) * $this->itemsPerPage;
}
public function render($urlPattern = '?page=:page') {
$totalPages = $this->getTotalPages();
$output = '<ul class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
$active = ($i == $this->currentPage) ? 'active' : '';
$url = str_replace(':page', $i, $urlPattern);
$output .= "<li class='page-item $active'><a class='page-link' href='$url'>$i</a></li>";
}
$output .= '</ul>';
return $output;
}
}
使用示例
// 使用分页类
$totalItems = 100; // 从数据库获取总记录数
$itemsPerPage = 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$pagination = new Pagination($totalItems, $itemsPerPage, $currentPage);
$offset = $pagination->getOffset();
// 数据库查询
$stmt = $db->prepare("SELECT * FROM articles LIMIT :offset, :limit");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $itemsPerPage, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll();
// 显示分页导航
echo $pagination->render();
这些方法可以根据实际需求进行调整和扩展,实现更复杂的分页功能。






