Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php 文章分页类

作者:仯孒①個亾哋杺¢涳孒   发布日期:2025-10-07   浏览:565

以下是一个简单的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生成分页链接,并可以根据当前页码计算出查询数据库时的偏移量。你可以根据自己的需求进行修改和扩展。

上一篇:php 检索字符(php全文检索)

下一篇:php访问网页输入密码(php记住密码)

大家都在看

php session用法

php 定义常量

phpisset函数

php html转图片

php后端

php爬虫框架

php读取csv文件

php+mysql动态网站开发

php 三元表达式

php文件加密

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站