Pagination is one of the most frequently used features for web applications. Wherever we have a bunch of data and need to show them as a list, we require pagination to prevent hundreds/thousands of data in a single page. As a robust framework, codeigniter provides very efficient way to handle it with its integrated support. In this tutorial, we will see, how we can implement codeigniter pagination and enhance it further as per our need.
This tutorial is based on the following 3 things:
1.Loading of the pagination class.
2.Setting the values of pagination array.
3.Calling the initialize() function of the pagination class.
For additional reference, check out the official codeigniter page: https://ellislab.com/codeigniter/user-guide/libraries/pagination.html
The code shown below demonstrates the controller function of the page you want to load:
$config['base_url'] = ‘http://www.example.com/index.php/default_page/’;
$config['no_rows'] = 100;
$config['_page'] = 10;
$this->pagination->initialize($config);
}
?>
To show the results in view, you must set a parameter for the $data array which contains the result returned from database. We will assume that, we have a model with a name “my_model” that consists a function named “fetch_my_data“. These are the functions that will return the result arary of the records that you want to fetch from database. Also, we will assume that, we have a view known as “my_view“, where the results will be displayed.
$data[‘my_result’] = $this->my_model->fetch_my_data($config['per_page'], $variant);
$this->load->view(‘my_view’, $data);
?>
Here, our work with the controlled is completely done. Now, lets move to the view file. Once, retrieving the data that was sent from the controller using HTML in view file, you should call the below function to show the following:
?>
The work is done here as well. The data that was just loaded from the database will get displayed in the view file & the pagination links will look like shown below:
« First Last »
Notice that the ‘10’ URL segment is the “$variant” variable that will be used in the “fetch_my_data()” model function to load the no of database rows that you need. The function should look like the below code:
return$query->result_array();
}
?>
In this example, links to 10 pages will appear, as we have previously set the “$config[‘no_rows’]” parameter to 100 and the “$config[‘_page’]” parameter to 10.
