codeigniter pagination – results remain same on every page

 

Questions


I’m using the Codeigniter pagination, but am encountering an issue.

The url changes on click, as in the limit updates e.g. displayAllUsers/10 to displayAllUsers/15, however the results remain same.

Here is my controller:

 public function displayAllUsers()
    {

        $this->load->model('backOfficeUsersModel');
        $data['loggedUser'] = $this->backOfficeUsersModel->get_by('username', $this->session->userdata('username'), FALSE,TRUE);

        $this->db->order_by('userid');
        $limit = 5;     // this works, I have 5 records displayed on the page
        $offset = 3;
        $this->db->limit($limit);
        $this->db->offset($offset);
        $data['users'] = $this->backOfficeUsersModel->get();

        // line bellow, prints correct result, 17 records total in database;
        $totalresults = $this->db->get('back_office_users')->num_rows();


        $this->load->library('pagination');
        $config['base_url'] = site_url('/backOfficeUsers/displayAllUsers');
        $config['total_rows'] = $totalresults;
        $config['per_page'] = 5;
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config); 
        $data['main_content'] = 'users';
        $data['title'] = 'Back Office Users';
        $errorMessage = FALSE;
        $this->load->vars($data,$errorMessage);
        $this->load->view('backOffice/template');

    } // end of function displayAllUsers

Anyone can spot what I am doing wrong?

 

 

————————————————-

Answer

Try doing your offset like this,

$offset = $this->uri->segment(3);
$this->db->limit(5, $offset);

This way when you access your users, you start from the correct offset.

Let’s assume that you have 20 users in your table. When you first land on the page your $offset variable will be empty as there is no trailing numbers in your link (at $this->uri->segment(3)). So when you query your database for 5 users you start from 0 as the $offset variable is empty. In this circumstance your code would be:

$this->db->limit(5, 0).

Get 5 records starting from the 0th record.

When you use the pagination links however, the per_page variable you set adds a number to the end of your url and reloads the page. When this happens, your $offset variable gets given a number, in this case, it adds 5 each time.
Now in this circumstance your code would be

$this->db->limit(5,5)

Meaning get 5 records, starting from the 5th record.

codeigniter,pagination

Facebook Comments

Post a comment