php实现分页类
PHP 分页类实现
分页是 Web 开发中常见的功能,用于将大量数据分割成多个页面显示。以下是一个简单的 PHP 分页类实现,包含基本功能如数据分页、页码生成和样式控制。
分页类代码
<?php
class Pagination {
private $totalItems; // 总记录数
private $itemsPerPage; // 每页显示记录数
private $currentPage; // 当前页码
private $pageRange; // 页码显示范围
private $totalPages; // 总页数
private $url; // 分页链接
public function __construct($totalItems, $itemsPerPage = 10, $currentPage = 1, $pageRange = 5, $url = '') {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
$this->pageRange = $pageRange;
$this->url = $url;
$this->totalPages = ceil($totalItems / $itemsPerPage);
}
public function getPagination() {
if ($this->totalPages <= 1) {
return '';
}
$start = max(1, $this->currentPage - floor($this->pageRange / 2));
$end = min($this->totalPages, $start + $this->pageRange - 1);
$html = '<ul class="pagination">';
// 上一页
if ($this->currentPage > 1) {
$html .= '<li><a href="' . $this->url . ($this->currentPage - 1) . '">上一页</a></li>';
}
// 页码
for ($i = $start; $i <= $end; $i++) {
$active = ($i == $this->currentPage) ? 'class="active"' : '';
$html .= '<li ' . $active . '><a href="' . $this->url . $i . '">' . $i . '</a></li>';
}
// 下一页
if ($this->currentPage < $this->totalPages) {
$html .= '<li><a href="' . $this->url . ($this->currentPage + 1) . '">下一页</a></li>';
}
$html .= '</ul>';
return $html;
}
}
?>
使用方法
<?php
// 示例数据
$totalItems = 100; // 总记录数
$itemsPerPage = 10; // 每页显示记录数
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$url = 'index.php?page=';
// 创建分页对象
$pagination = new Pagination($totalItems, $itemsPerPage, $currentPage, 5, $url);
// 显示分页
echo $pagination->getPagination();
?>
数据库查询示例
<?php
// 数据库分页查询
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$offset = ($currentPage - 1) * $itemsPerPage;
$stmt = $db->query("SELECT * FROM table LIMIT $offset, $itemsPerPage");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 显示数据
foreach ($rows as $row) {
echo $row['id'] . ' ' . $row['name'] . '<br>';
}
// 显示分页
echo $pagination->getPagination();
?>
样式定制
可以自定义 CSS 样式来控制分页的外观:
.pagination {
display: inline-block;
padding: 0;
margin: 20px 0;
}
.pagination li {
display: inline;
margin: 0 5px;
}
.pagination li a {
color: #333;
padding: 8px 16px;
text-decoration: none;
border: 1px solid #ddd;
}
.pagination li.active a {
background-color: #4CAF50;
color: white;
border: 1px solid #4CAF50;
}
.pagination li a:hover:not(.active) {
background-color: #ddd;
}
功能扩展
- 添加首页和末页:可以在分页中添加首页和末页链接,方便用户快速跳转。
- AJAX 分页:通过 JavaScript 实现无刷新分页,提升用户体验。
- 多语言支持:根据用户语言环境显示不同的分页文字。
- URL 美化:使用 URL 重写技术美化分页链接。
这个分页类提供了基本功能,可以根据实际需求进行扩展和定制。







