CI 分页类的使用

分页本身很简单,无非就是一个 [limit $offset, $length] 的过程。
$length 是每页显示的数据量,这个是固定的。要确定的就只有 $offset了。
在CI中的分页类同样要依据这个来做,他在选择 offset 依据时有两种可选方式:
(1)在url中填入offset,这个参数可以直接作为从数据库中取数据的 $offset 值
(2)在url中填入当前的页码,$offset = ($cur_page-1) * $length
实质上,两者是一致的。只是计算的方式不同:
(1)limit $offset, $per_page2)limit ($cur_page-1) * $per_page, $per_page 
理解了这个,CI的分页类就很容易使用了。采用哪种方式是通过该类中下面的这个属性来做的:
var $use_page_numbers    = FALSE; // Use page number for segment instead of offset
默认是使用方式(2)。

要使用该类,最重要的还是要清楚我们需要怎样的一个URL,根据该URL要获取哪些信息。
这里以 /controller/method/ 为例子,要在method中分页,应该是要构造这样的URL:
    /controller/method/123/4        // 123是数据的id, 4 可以是 (1)$offset 或者 (2)$cur_page
那么。就这样配置分页类的数据(这里采用了默认的方式):
    public function method($cat_id = 0, $offset=0) {
        $config['base_url'] = base_url('controller/method/' . $cat_id);
        $config['total_rows'] = $this->some_model->get_tb_count($cat_id);
        $config['per_page'] = 2;
        $config['uri_segment'] = 4;    // 分页信息在 segment 段中的位置。 这里是 /controller/method/$cat_id/$_page_sg
        $this->pagination->initialize($config);$all_data = $this->some_model->get_data_limited($cat_id, $config['per_page'], $offset);
    }
上面最后这一句对应的函数应该是这样的:
    public function get_data_limited($cat_id=-1, $offset, $length) {
        return $this->db
                     ->select('pc.photopicid, pc.title, pc.smallpic, pc.bigpic')
                    ->from('t_photo p')
                    ->join('t_photopic pc', 'pc.photoid=p.photoid', 'inner')
                    ->where(array('p.classid'=>intval($cat_id), 'pc.isclose'=>0))
                    ->limit($offset, $length)        //这里取分页数据
                    ->get()
                    ->result_array();
    }


要对其进行定制也很容易了。。

 

posted @ 2016-07-20 14:31  1678924929  阅读(2104)  评论(0编辑  收藏  举报