5
votes

I have read all questions on Stackoverflow and have seen no definitive answer to the question. I am currently using the codeigniter pagination library to generate my pagination links using a limit and an offset:

$config['base_url'] = base_url() . 'explore/featured/index/';
    $config['total_rows'] = $this->Projects_model->get_featured_count();//Count featured projects
    $config['per_page'] = 12;
    $config['uri_segment'] = 4;
    $config['display_pages'] = FALSE;
    $config['next_link'] = 'Older →';
    $config['prev_link'] = '← Newer';
    $this->pagination->initialize($config);
    $limit = $config['per_page'];
    $offset = $this->uri->segment(4);

    $data['pagination'] = $this->pagination->create_links();

    $data['projects'] = $this->Projects_model->get_featured($limit, $offset); //get featured projects from database

The above code limits the output values of my query and uses an offset that is contained in my 4th URI segment.

How can I change the below code to page numbers??? Appears to be impossible because i would be no longer able to use an offset in my url.

4

4 Answers

18
votes

At some point, CI updated their pagination library to (finally) accommodate for this:

$config['use_page_numbers'] = TRUE;

By default, the URI segment will use the starting index for the items you are paginating. If you prefer to show the the actual page number, set this to TRUE.

If you are on a version that does not have this feature and are unable to update your entire CI installation, you should be able to just drop in the latest pagination library.

To calculate your DB offset, use $limit * $page_number where "page_number" is the value in your URL (4th segment in your case).

7
votes

$limit * $page_number mentioned above didn't return a true offset as a starting point and created problems when the page number is 1 because the offset must be 0 by then. This worked for me:

$offset = ($page_number  == 1) ? 0 : ($page_number * $config['per_page']) - $config['per_page'];
4
votes

Just use:

$offset = ($this->uri->segment(4)) ? $this->uri->segment(4) : 1;
$data['projects'] = $this->Projects_model->get_featured($limit, $limit*($offset-1));
-1
votes
$page_num = $this->uri->segment(1);
$offset = ($page_num  == NULL) ? 0 : 
          ($page_num * $config['per_page']) - $config['per_page'];