Php – How to use page numbers in Codeigniter pagination instead of offset

codeigniterMySQLpaginationPHP

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.

Best Answer

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).

Related Topic