以下是一个简单的PHP文章分页类的示例代码:
class Pagination {
private $limit;
private $totalRecords;
private $currentPage;
private $url;
public function __construct($limit, $totalRecords, $currentPage, $url) {
$this->limit = $limit;
$this->totalRecords = $totalRecords;
$this->currentPage = $currentPage;
$this->url = $url;
}
public function getOffset() {
return ($this->currentPage - 1) * $this->limit;
}
public function getTotalPages() {
return ceil($this->totalRecords / $this->limit);
}
public function generateLinks() {
$totalPages = $this->getTotalPages();
$links = '';
if ($totalPages > 1) {
$links .= '<ul class="pagination">';
if ($this->currentPage > 1) {
$links .= '<li><a href="' . $this->url . '&page=' . ($this->currentPage - 1) . '">上一页</a></li>';
}
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $this->currentPage) {
$links .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$links .= '<li><a href="' . $this->url . '&page=' . $i . '">' . $i . '</a></li>';
}
}
if ($this->currentPage < $totalPages) {
$links .= '<li><a href="' . $this->url . '&page=' . ($this->currentPage + 1) . '">下一页</a></li>';
}
$links .= '</ul>';
}
return $links;
}
}
使用示例:
$limit = 10; // 每页显示的记录数
$totalRecords = 100; // 总记录数
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1; // 当前页码
$url = 'articles.php'; // 当前页面的URL
$pagination = new Pagination($limit, $totalRecords, $currentPage, $url);
$offset = $pagination->getOffset(); // 获取当前页的偏移量
$totalPages = $pagination->getTotalPages(); // 获取总页数
$links = $pagination->generateLinks(); // 生成分页链接
// 根据偏移量查询数据库获取当前页的文章列表
$query = "SELECT * FROM articles LIMIT $limit OFFSET $offset";
// 执行查询并输出文章列表
// ...
// 输出分页链接
echo $links;
这个示例中的分页类可以根据当前页码、每页显示的记录数、总记录数和当前页面的URL生成分页链接,并可以根据当前页码计算出查询数据库时的偏移量。你可以根据自己的需求进行修改和扩展。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站