控制器里:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $this->load->model('review_model'); $this->load->library('pagination'); //设定分页的根链接 $config['base_url'] = site_url('review/show/'.$gid); //进行查询内容计算总数 $reviewinfo_temp = $this->review_model->GetGoodsRevobject($gid); $config['total_rows'] = $reviewinfo_temp->num_rows(); //每页显示多少条记录 $config['per_page'] = 20; $config['uri_segment'] = 4; $config['first_link'] = '首页'; $config['last_link'] = '尾页'; $config['full_tag_open'] = '<p>'; $config['full_tag_close'] = '</p>'; $this->pagination->initialize($config); //传参数给VIEW $data['page_links'] = $this->pagination->create_links(); //再次查询,得到需要显示的数据 $review = $this->review_model->GetGoodsRevobject($gid,$config['per_page'],$this->uri->segment(4)); //下面载入VIEW不写了 //...... |
从上面设定分页的base_rul可以看出来,模型函数需要三个参数,一个gid是必须的,另两个用有limit语句里,模型代码:
1 2 3 4 5 6 7 8 9 | //这里$num和$offset默认参数为空 function GetGoodsRev($gid=NULL,$num="",$offset="") { $this->db->limit($num,$offset); $this->db->where("gid",$gid); $this->db->order_by("rpubdate", "desc"); $query = $this->db->get($this->config->item('db_prefix').'review'); return $query; } |
视图很简单,只有在需要添加分页链接的地方写一句:
1 2 | //这个变量名称要和控制器里传过来的对应。 <?php echo $page_links;?> |
CodeIgniter的分页类对内容分页很方便,不过,从上面也可以看到,分页效率很低。在不分页的情况下,只需要进行一次数据库查询,现在需要两次。我正在考虑能不能优化一下,也许接下来的博客里会提到。敬请关注。