I was trying to do pagination in CodeIgniter but I did something wrong I guess.
My codes are below.
blog_model
function posts($cat_id='')
{
$config['base_url'] = 'http://example.com/blog';
$config['total_rows'] = 3;
$config['per_page'] = 1;
$config['num_links'] = 20;
$this->pagination->initialize($config);
if($cat_id) $this->db->where('cat_id',$cat_id);
$query = $this->db->get('posts', $config['per_page'], $this->uri->segment(3));
return $query->result();
}
blog_view
<?php echo $this->pagination->create_links(); ?>
Pagination in CI can get tricky. Pagination simply constructs the links, you'll still have to properly construct the limit
and offset
for the database query.
You must pass the page number into your function from the URL
function posts($cat_id='', $page = FALSE)
{
$config['base_url'] = 'http://example.com/blog';
$config['total_rows'] = 3;
$config['per_page'] = 1;
$config['num_links'] = 20;
$config['uri_segment'] = 3; // <- verify this one
$this->pagination->initialize($config);
// set the page to 1 if the page is missing from the URL
$page = ($page === FALSE ? 1 : $page);
// calculate the offset for the query
$offset = ($page - 1 ) * $config['per_page'];
if($cat_id) $this->db->where('cat_id',$cat_id);
$query = $this->db->get('posts', $config['per_page'], $offset);
return $query->result();
}
EDIT as per comments:
I am also not sure your segment 3 is correct for the location of the page number. If it's /blog/posts/cat_id/1
, then the page number (your offset) is at segment number 4.