phpcodeigniterpaginationcodeigniter-3

Codeigniter Pagination Show Number of Results & Page


I am using Codeigniter 3 and have a simple PHP application.

Using the pagination class I would like to display the following at the top of each of my pages;

Showing x to y of z results

Where;

x = start row
y - end row
z = total rows

`Showing 1 to 10 of 5213 results.`
`Showing 11 to 20 of 5213 results.`
`etc`

I am able to retrieve the total rows using the $config['total_rows'] variable. Not sure about the rest though.

My items.php controller looks like this;

    public function index() {
        $config['base_url'] = '/items/index';
        $config['use_page_numbers'] = FALSE; 
        $config['reuse_query_string'] = TRUE;
        $config['total_rows'] = $this->db->get('item')->num_rows();
        $config['per_page'] = 10;
        $config['num_links'] = 10;
        $config['full_tag_open'] = '<div><ul class="pagination">';
        $config['full_tag_close'] = '</ul></div><!--pagination-->';
        $config['first_link'] = '&laquo; First';
        $config['first_tag_open'] = '<li class="prev page">';
        $config['first_tag_close'] = '</li>';
        $config['last_link'] = 'Last &raquo;';
        $config['last_tag_open'] = '<li class="next page">';
        $config['last_tag_close'] = '</li>';
        $config['next_link'] = 'Next &rarr;';
        $config['next_tag_open'] = '<li class="next page">';
        $config['next_tag_close'] = '</li>';
        $config['prev_link'] = '&larr; Previous';
        $config['prev_tag_open'] = '<li class="prev page">';
        $config['prev_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="active"><a href="">';
        $config['cur_tag_close'] = '</a></li>';
        $config['num_tag_open'] = '<li class="page">';
        $config['num_tag_close'] = '</li>';
        $config['anchor_class'] = 'follow_link';
        $this->load->library('pagination');
        $this->pagination->initialize($config);

        $data = array(
        'items' => $this->items_model->itemList()
        );

        $this->load->view('item_list', $data);
    }

My URLs are in the following format;

items/index    // displays results 1-10
items/index/10 // displays results 11-20
items/index/20 // displays results 21-30

Any help would be appreciated. Thanks


Solution

  • $data['z'] = $config['total_rows'];
    
    $data['x'] = (int)$this->uri->segment(3) + 1;
    
    if ($this->uri->segment(3) + $config['per_page'] > $config['total_rows']) {
        $data['y'] = $config['total_rows'];
    } else {
        $data['y'] = (int)$this->uri->segment(3) + $config['per_page'];
    }
    

    Also, you can make one check before loading view if requested page is in range and if it is not you should redirect visitor to first or last page as per your requirement.