How to do pagination in codeigniter ?

In this article I will explain you how to do pagination in codeigniter. Codeigniter’s Pagination class is very easy to use.
To do pagination in codeigniter first you need to autoload the pagination library.
Here is a simple example showing how to create pagination in one of your controller functions:
Create a controller name My_controller.php and place in the controller folder

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class My_controller extends CI_Controller {
  5.  
  6. public function __construct() {
  7.  
  8. parent::__construct();
  9. //here we will autoload the pagination library
  10. $this->load->library('pagination');
  11. }
  12. public function paginationExample()
  13. {
  14. //echo $this->uri->segment(2);die;
  15.  
  16. $config = array();
  17. $config["base_url"] = base_url('My_controller/paginationExample');
  18. $config['total_rows'] = $this->db->count_all("Your table");//here we will count all the data from the table
  19. $config['per_page'] = 5;//number of data to be shown on single page
  20. $config["uri_segment"] = 2;
  21. $this->pagination->initialize($config);
  22. $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
  23. $data["allData"] = $this->My_model->paginationExample($config["per_page"], $page);
  24. $data["links"] = $this->pagination->create_links();//create the link for pagination
  25. $this->load->view('your view',$data);
  26. }
  27. }

The $config array contains your configuration variables. It is passed to the $this->pagination->initialize function
Now create a model name My_model.php and place in the model folder.Here we will select the data from table according to the pagination.

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class My_model extends CI_model{
  5.  
  6. public function __construct() {
  7.  
  8.  
  9. }
  10.  
  11. public function paginationExample($limit, $start)
  12. {
  13. $this->db->limit($limit, $start);//here we will set the limit according to the value you will get from your controller function
  14. $this->db->select('*');
  15. $this->db->from('Your table');
  16. return $this->db->get()->result();
  17. }
  18. }

Now in the view file just echo the link

<div><?php echo $links; ?></div>

if there will be more then five record in your table it will automatically create pagination.

Hope this small articale of how to do pagination in codeigniter will help you. Keep reading.