You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为CodeIgniter添加分页?附现有控制器代码示例

在CodeIgniter中给产品列表添加分页功能

我来一步步帮你实现分页功能,总共分三个部分修改:控制器、模型和视图,操作起来很清晰~

1. 修改控制器代码

我们需要完善分页配置,同时把当前页码传递给模型,获取对应页的数据:

<?php 
class Product_details extends CI_Controller{
    function index(){
        // 加载分页类和模型
        $this->load->library('pagination');
        $this->load->model('product_model');

        // 分页核心配置
        $config['base_url'] = base_url('product_details/index'); // 分页链接的基础URL
        $config['total_rows'] = $this->product_model->get_total_products(); // 总产品数量
        $config['per_page'] = 20; // 每页显示20条数据
        $config['num_links'] = 5; // 分页栏显示的页码数量

        // 可选:添加分页样式适配(比如Bootstrap风格)
        $config['full_tag_open'] = '<ul class="pagination">';
        $config['full_tag_close'] = '</ul>';
        $config['first_link'] = '首页';
        $config['last_link'] = '末页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['cur_tag_open'] = '<li class="active"><a>';
        $config['cur_tag_close'] = '</a></li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';

        // 初始化分页配置
        $this->pagination->initialize($config);

        // 获取当前页码(URL第3段,默认从0开始)
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        // 获取当前页的产品数据
        $data['userArray'] = $this->product_model->return_products($page, $config['per_page']);
        // 生成分页链接
        $data['pagination_links'] = $this->pagination->create_links();

        // 加载视图
        $this->load->view('product_listing',$data);
    }
}

2. 修改Product_model模型

需要新增两个方法:一个统计总产品数,另一个根据分页参数获取对应数据:

<?php
class Product_model extends CI_Model{
    // 获取产品总数(用于计算分页页数)
    public function get_total_products(){
        // **请替换成你的实际产品表名**
        return $this->db->count_all('products');
    }

    // 按分页参数获取产品数据
    public function return_products($offset = 0, $limit = 20){
        // **请替换成你的实际产品表名**
        $query = $this->db->get('products', $limit, $offset);
        return $query->result_array();
    }
}

如果你的产品查询原本带有条件(比如WHERE筛选),记得把相同的条件同步到get_total_products()方法里,确保统计的总数和实际查询结果匹配。

3. 修改视图代码

在产品列表表格下方添加分页链接,同时确保表格正常遍历数据:

<table>
    <tr>
        <th>ID</th>
        <!-- 你的其他表头字段 -->
    </tr>
    <?php foreach($userArray as $product): ?>
    <tr>
        <td><?php echo $product['id']; ?></td>
        <!-- 你的其他产品字段渲染 -->
    </tr>
    <?php endforeach; ?>
</table>

<!-- 显示分页导航 -->
<div class="pagination-container">
    <?php echo $pagination_links; ?>
</div>

这样就完成啦!现在访问页面时,会自动按每页20条展示产品,点击分页链接就能切换不同页面。

内容的提问来源于stack exchange,提问作者Reezal AQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:37:12