Thursday, 12 July 2012

codeigniter pagination with search

This is the    simple way to create the search function using pagination in codeigniter. it should be helpfull to those who need the search with pagination..

Controller




function search_category()
{
$post = $this->input->post('search');
if(!$post){
$post=$this->uri->segment(3);
}

        $this->session->set_userdata('ser', $post);
$this->load->model('category_model');
$per_page = 2;
    $total = $this->category_model->search_query_count();
    $data['categoryList'] = $this->category_model->search_query($per_page, $this->uri->segment(4));
  $this->load->library('pagination');
  $base_url = base_url().'category/search_category/'.$post;
    $config['base_url'] = $base_url;
    $config['total_rows'] = $total;
    $config['per_page'] = $per_page;
    $config['uri_segment'] = '4';
$this->pagination->initialize($config);
$data['inactive'] = $this->category_model->inactive_category();
$data['active'] = $this->category_model->active_category();
$data['main_content']='category_list';

$this->load->view('includes/template', $data);
}


Model
function search_query_count()
{
$post = $this->session->userdata('ser');
echo $post;
$query  = $this->db->query('select count(id) as count from category where name LIKE "%'.$post .'%" or description like "%' . $post .'%"');
   foreach($query->result() as $row)
   {
  return $row->count;
   }
}
function search_query($limit = NULL, $offset = NULL)
{
$post = $this->session->userdata('ser');
echo $post;
if(!$offset)
{
$offset = 0;
}
echo $offset;
$this->db->select('*');
$this->db->from('category');
$this->db->like('name', $post);
       $this->db->or_like('description', $post);
       $this->db->order_by("id", "desc");
       $this->db->limit($limit, $offset);
       $query = $this->db->get();
       return $query->result();
}

2 comments: