Codeigniter分页问题

时间:2010-08-27 13:01:54

标签: codeigniter pagination limit offset

我基本上无法让分页位工作,我在更改数据库查询之前就做了,现在我已经卡住了。

我的模型看起来像:

function get_properties($limit, $offset) {
   $location = $this->session->userdata('location');
   $property_type = $this->session->userdata('property_type');
   if($property_type == 0) 
   {
      $sql = "SELECT * FROM properties ";
   }
   // more queries here
   $sql .= " LIMIT ".$limit.", ".$offset.";";
   $query = $this->db->query($sql);
   if($query->num_rows() > 0) {
      $this->session->set_userdata('num_rows', $query->num_rows());
      return $query->result_array();    
      return FALSE;
      }
   }
} 

我的控制器看起来像:

function results() {
   $config['base_url'] = base_url().'/properties/results';
   $config['per_page'] = '3';
   $data['properties_results'] = $this->properties_model->get_properties($config['per_page'], $this->uri->segment(3));
   $config['total_rows'] = $this->session->userdata('num_rows');
   $this->pagination->initialize($config);
   $config['full_tag_open']='<div id="pages">';
   $config['full_tag_close']='</div>';
   $data['links']=$this->pagination->create_links();
   $this->load->view('properties_results',$data);
} 

请帮忙......搞砸了!

1 个答案:

答案 0 :(得分:1)

它不起作用的原因是你永远不会得到total_rows。您通过此查询获得total_rows,但它已经有一个偏移量和一个限制:

$sql .= " LIMIT ".$limit.", ".$offset.";";
$query = $this->db->query($sql);

要解决此问题,您应该为模型添加一个功能:

function get_all_properties()
{
    return $this->db->get('properties');
}

然后在你的控制器中,而不是:

$config['total_rows'] = $this->session->userdata('num_rows');

执行:

$config['total_rows'] = $this->properties_model->get_all_properties()->num_rows();

这应该可以修复你的分页。除此之外,你的代码有一些奇怪的东西。例如。 return FALSE;中的get_properties将永远不会执行。为什么要在会话中存储如此多的数据?在我看来,这不是必要的,也不是一个好主意。

相关问题