How to create Pagination in Codeigniter?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
How to create Pagination in Codeigniter?

Today in this blog, I will teach you how to create pagination links in codeigniter application. Here we will use pagination library for creating our pagination links in codeigniter application.

Now you have to display large number of records from database table. So if you show the all records. Then we have a lots of data and need to show them, then it allows you to navigate from page to page, on that time we must require pagination

Step 1 : Download Codeigniter Project

In this first step we need to downlaod codeigniter project on codeigniter official site. After Download need to unzip the setup in your local system xampp/htdocs/. And change the name of download folder “test”.

Step 2 : Basic Configuration

Now in this step we will set the some basic configuration on our config.php file.

application/config/config.php

$config['base_url'] = 'http://localhost/test/';
Step 3 : Create Route

Now in this step we will create route in routes.php file And also put the bellow code.

application/config/routes.php

$route['users/(:num)'] = 'users';
Step 4 : Create Database and Table

Now in this step we need to create database. So create database after perform bellow sql query for create table in your database.

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable test table' AUTO_INCREMENT=1;
 
 
INSERT INTO users(id, name, email, mobile_number, created_at) VALUES
  (1, 'abc', 'abc@gmail.com', '1234657890', '2019-12-12'),
  (2, 'xyz', 'xyz@gmail.com', '9564862132', '2019-12-11'),
  (3, 'mno', 'mno@gmail.com', '9869899644', '2019-12-10'),
  (4, 'cates', 'cates@yahoo.com', '9800015688', '2019-12-04'),
  (5, 'def', 'def@gmail.com', '9865327845', '2019-12-05'),
  (6, 'ghi', 'ghi@gmail.com', '9865327845', '2019-12-06'),
  (7, 'jjj', 'jjj@gmail.com', '7845128956', '2019-12-07'),
  (8, 'John', 'john@gmail.com', '8978455689', '2019-12-08'),
  (9, 'Merry', 'merry@gmail.com', '6589784565', '2019-12-09'),
  (10, 'Keliv', 'kelvin@gmail.com', '6325416398', '2019-12-10'),
  (11, 'Herry', 'herry@gmail.com', '9876542314', '2019-12-11'),
  (12, 'Mark', 'mark@gmail.com', '8976541235', '2019-12-12');
Step 5 : Setup Database configuration

at this step, we need to connect our project to our database. Fill our server details in database.php.

application/config/database.php

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'test',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);
Step 6 : Create Model

Now in this step you can create model file. So In this model we will get all users list by using list() function.

we will get all counts of users by using totalUsers() function.

<?php
class User_model extends CI_Model {
  
    public function __construct()
    {
        $this->load->database();
    }
     
    public function list($limit, $offset)
    {
      $this->db->select("*");
      $this->db->from('users');
      $this->db->limit($limit, $offset);
      $query = $this->db->get();
      return $query->result();
    }
 
    function totalUsers(){
      return $this->db->count_all_results('users');
   }
     
}
Step 7 : Create Controller

So in this step we need to create controller file. In controller we can create some method/function.

application/controllers/Users.php

<?php
class Users extends CI_Controller {
  
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->helper('url_helper');
        $this->load->library('pagination');
    }
  
    public function index($offset=0)
    {    
        $config['total_rows'] = $this->user_model->totalUsers();
   
        $config['base_url'] = base_url()."users";
        $config['per_page'] = 5;
        $config['uri_segment'] = '2';
          
        $config['full_tag_open'] = '';
        $config['full_tag_close'] = '';
          
        $config['first_link'] = '« First';
        $config['first_tag_open'] = '';
        $config['first_tag_close'] = '';
          
        $config['last_link'] = 'Last »';
        $config['last_tag_open'] = '';
        $config['last_tag_close'] = '';
          
        $config['next_link'] = 'Next ?';
        $config['next_tag_open'] = '';
        $config['next_tag_close'] = '';
          
        $config['prev_link'] = '? Previous';
        $config['prev_tag_open'] = '';
        $config['prev_tag_close'] = '';
          
        $config['cur_tag_open'] = '';
        $config['cur_tag_close'] = '';
          
        $config['num_tag_open'] = '';
        $config['num_tag_close'] = '';
 
        $this->pagination->initialize($config);
          
        $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
 
        $query = $this->user_model->list($config["per_page"], $page);
            
        $data['users'] =  $query;
 
        $data['title'] = 'User List';
 
        $this->load->view('list', $data);
    }
}
Step 8 : Create View File

Now we are in last step. In this step you need to create view file list.php. Here put the bellow code.

application/controllers/Users.php

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter Google Recaptcha Form Validation Example - Tutsmake.com</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
   <div class="container">
  <div class="row mt40">
     <table class="table table-bordered">
       <thead>
          <tr>
             <th>Id</th>
             <th>Name</th>
             <th>Email</th>
             <th>Mobile</th>
          </tr>
       </thead>
       <tbody>
          <?php if($users): ?>
          <?php foreach($users as $user): ?>
          <tr>
             <td><?php echo $user->id; ?></td>
             <td><?php echo $user->name; ?></td>
             <td><?php echo $user->email; ?></td>
             <td><?php echo $user->mobile_number; ?></td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
     </table>
      <div class="row">
      <div class="col-md-12">
      <div class="row"><?php echo $this->pagination->create_links(); ?></div> 
     </div>
  </div>
</div>
</div>
</body>
</html>

Read Also : Upload image and create thumbnail in codeigniter – example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →