Codeigniter Pagination Library Example

In this pagination tutorial, we would love to share with you how to use pagination to show data on an HTML table with pagination links in CodeIgniter.

Codeigniter Pagination Library Example

Here are steps:

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Define Route
  • Setup Database Credentials
  • Create User Model
  • Create New Controller
  • Create View
  • Test This Project

Download Codeigniter Project

In this step, we will download the latest version of Codeigniter, Go to this link Download Codeigniter download the fresh setup of Codeigniter and unzip the setup in your local system xampp/htdocs/.

Basic Configurations

Set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor, and configure like the following:

$config['base_url'] = 'http://localhost/demo/';

Define Route

Next we will define routes in routes.php file, so let’s go to application/config/route.php and open this file on text editor. Put the below line into this file.

$route['users/(:num)'] = 'users';

Create Database With Table

Runt he following query to create table in 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 demo table' AUTO_INCREMENT=1;
INSERT INTO users(id, name, email, mobile_number, created_at) VALUES
  (1, 'Team', '[email protected]', '9000000001', '2019-01-01'),
  (2, 'Admin', '[email protected]', '9000000002', '2019-01-02'),
  (3, 'User', '[email protected]', '9000000003', '2019-01-03'),
  (4, 'Editor', '[email protected]', '9000000004', '2019-01-04'),
  (5, 'Writer', '[email protected]', '9000000005', '2019-01-05'),
  (6, 'Contact', '[email protected]', '9000000006', '2019-01-06'),
  (7, 'Manager', '[email protected]', '9000000007', '2019-01-07'),
  (8, 'John', '[email protected]', '9000000055', '2019-01-08'),
  (9, 'Merry', '[email protected]', '9000000088', '2019-01-09'),
  (10, 'Keliv', '[email protected]', '9000550088', '2019-01-10'),
  (11, 'Herry', '[email protected]', '9050550088', '2019-01-11'),
  (12, 'Mark', '[email protected]', '9050550998', '2019-01-12');

Setup Database Credentials

Set up database details in application/config/database.php file:

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'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
);

Create User Model

Create a User_model.php file in application/models/ that handles fetching data from the database.

<?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');
   }

}

Create New Controller

Create a controller name Users.php and methods into it to handle paganation on server side:

<?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'] = '<div class="pagination"><ul>';
          $config['full_tag_close'] = '</ul></div>';

          $config['first_link'] = '« First';
          $config['first_tag_open'] = '<li class="prev page">';
          $config['first_tag_close'] = '</li>';

          $config['last_link'] = 'Last »';
          $config['last_tag_open'] = '<li class="next page">';
          $config['last_tag_close'] = '</li>';

          $config['next_link'] = 'Next →';
          $config['next_tag_open'] = '<li class="next page">';
          $config['next_tag_close'] = '</li>';

          $config['prev_link'] = '← 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>';
         $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);
    }
}

Create View

Create list.php view file in application/views/ folder to show data with pagination:

<!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 pagination 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>

Test This Project

For start development server, Go to the browser and hit below the url.

http://localhost/demo/users

Conclusion

In this codeigniter pagination tutorial, We have successfully created users list with pagination.

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *