Pagination in CodeIgniter

Hello Guys! Today I'm going to explain a simple application based on CodeIgnite Pagination. I think you are aware of pagination word. It simply means showing the page numbers. Here I will fetch data from a database and display them in the front end. In addition to that I will create pagination for those records and then it will automatically fetch results and display according to the way I include. In PHP, not only in CodeIgniter pagination is  bit difficult to implement. Even with CodeIgniter, you have to include a bunch of code lines to implement pagination for your project. But being a framework, CI makes our work easier and creates pagination for us.

Download Source Code : GitHub

First create a database to store the data. My database is called "pagination" and it will be having a table called "users" with the following format.

Label name => DB column name => Data type
Index => indexno => INT
Username => username => VARCHAR
Email => email => VARCHAR

SQL Code :

CREATE TABLE `users` (
  `indexno` int(10) NOT NULL,
  `username` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Create a controller, model and a view to start the project. In my case,
Controller => Users.php
Model => User_model.php
View => user_view.php

Configure Bootstrap in CodeIgniter using  link.

Then you have to do the basic configurations for CI. I have already published about them in my blog. Click on this link to see them.
Configure database file in config folder by giving your DB details. In autoload file, you need only url helper and database library. If you are following me, give the default controller in routes file, as Users. Configure base url in config folder by giving your project name correctly. My base_url( ) is like this:
$config['base_url'] = 'http://localhost/Projects/CIPagination';

Now  you are all set. Next part is to start coding your project. First of all I'd like to say this is a bit long article due to the special things related with this part. Let's start!

Load the model in your controller.

    public function __construct()
    {
      parent::__construct();
      $this->load->model('User_model');

    }

First we will move to the view file. We have to arrange the fetched results in a table. For that, I will use this kind of layout for this page.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CodeIgniter Pagination</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css">       
        <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">
        <style type="text/css">
            body {
                font-family: 'Source Sans Pro', sans-serif;
                font-size: 16px;
            }
            #wrapper {
                padding: 20px;
            }
        </style>
    </head>
  <body>


      <div id="wrapper">

        <h1>CodeIgniter Pagination</h1>
        <br>

        <div class="row">
            <div class="col-lg-12">
                <div class="table-responsive table-bordered">
                    <table class="table">

                    <tr>
                        <th>Index</th>
                        <th>Userame</th>
                        <th>Email</th>
                        <th>Change</th>
                        <th>Remove</th>
                    </tr>`
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                       <td>
                         <a href="#"><button type='submit' class='btn btn-primary'>update</button></a>                                </td>
                        <td>
                          <a href="#"><button type='submit' class='btn btn-danger'>Delete</button></a>
                        </td>
        
                    </table>
                </div>
                <br>
                  
            </div>
        </div>
        
        
          
        </div>

    <!-- JavaScript -->


    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   
    <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>
  </body>
</html>
This view loads the records in a table with the two options update and delete for each record. Those options will not be done in this tutorial. They are just buttons only. Keep the view as it is for now. Let's move to the model.

Model is the key component in this tutorial since it is the one who retrieves data to format our pagination properly. In the model, we need to create 3 main functions. They are for getting records count, getting all records and getting records per page. Let's create them.

User_model full code :

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends CI_Model{

    //getting all users

    public function getUsers() { 
        
            $this->db->select('*');
            $this->db->from('users');
            $this->db->order_by('indexno');
            $query = $this->db->get();
            return $query->result();
        
    }

    //getting users per page

    public function getUserPagintaion($limit, $start) {
        
            $this->db->select('*');
            $this->db->from('users');
            $this->db->limit($limit, $start);
            $this->db->order_by('indexno');
            $query = $this->db->get();
            return $result = $query->result();
        
    }

    //getting users count

    public function getUserCount() {
        
            $this->db->select("COUNT(*) as num_row");
            $this->db->from('users');
            $this->db->order_by('indexno');
            $query = $this->db->get();
            $result = $query->result();
            return $result[0]->num_row;

    }


}

Now, the model function are set. It's all about SQL. These functions will be used next in the Users controller.

Configuring the controller is the most difficult part. It has so many configurations. First I will put the code here ans then explain. I think it is OK.

Users full code :

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Users extends CI_Controller{

    public function __construct()
    {
      parent::__construct();
      $this->load->model('User_model');

    }
    
    public function index() {

        $this->load->library('pagination');
        $config['base_url'] = 'http://localhost/Projects/CIPagination/Users/index';
        $config['total_rows'] = $this->User_model->getUserCount();
        $config['per_page'] = 5;
        $config['uri_segment'] = 3;
        $config['full_tag_open'] = '<ul class="pagination pagination-lg">';
        $config['full_tag_close'] = '</ul>';
        $config['attributes'] = array('class' => 'page_link');
        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['prev_link'] = '&laquo';
        $config['prev_tag_open'] = '<li class="prev">';
        $config['prev_tag_close'] = '</li>';
        $config['next_link'] = '&raquo';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="page-item active"><a href="#" class="page-link">';
        $config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $this->pagination->initialize($config);
        $data['link'] = $this->pagination->create_links();
        $data['users'] = $this->User_model->getUserPagintaion($config['per_page'], $page);
        $this->load->view('user_view', $data);
        
    }


}

Here I have coded the logic within the index function, since I have no any other functions for this tutorial. Now we can move to the explanation. 

You can see a number of $config[''] lines in this code. Those are defined by CI to configure the pagination. Don't think too much of it and DON'T CHANGE their names within the quotation marks. Fist you need to load the pagination library provided by CI framework. Then give the base url for this pagination part as I mentioned.

$config['total_rows'] = $this->User_model->getUserCount();
This  is the way to get users count through the model. It takes the count of all users. Nothing special
here since it is the same way of loading a model function.

$config['per_page'] = 5;
This configuration determines the number of users displayed on a single page. Give any number.

$config['uri_segment'] = 3;
This is bit different. URI segment  simply means the way of displaying URL. It is assigned as 3. So, there are 3 section in the URL like this.

http://example.com/news/local/metro/crime_is_up

Then the numbers will go like this;
  1. news
  2. local
  3. metro
  4. crime_is_up

Here URI segment is equal to 4. In our project it was assigned as 3. Simply it means the controller, function, parameter.
  1. Controller    => segment1
  2. Function      => /segment2
  3. Parameters  => /segment3/
Contruction of URL: ....................../segment1/segment2/segment3

our URL will be formatted in this way : 
http://localhost/Projects/CIPagination/Controller/Function/Parameters

Then you can see set of line including HTML tag values. These are the lines that create the styles for pagination. It means the way how the pagination is displayed. Here I have used Bootstrap pagination. This is a normal Bootstrap HTML pagination.

  <ul class="pagination pagination-lg">
<li class="disabled">
<span>
<span aria-hidden="true">&laquo;</span>
</span>
</li>
<li class="active">
<span>1 <span class="sr-only">(current)</span></span>
</li>
    <li class="disabled">
<span>
<span aria-hidden="true">&r aquo;</span>
</span>
</li>
</ul>
Now we are going to make this kind of format using CI pagination configurations. All the following links does this job. The config names have been named by CI according to the job it does. It is easy to understand.

        $config['full_tag_open'] = '<ul class="pagination pagination-lg">';
        $config['full_tag_close'] = '</ul>';
        $config['attributes'] = array('class' => 'page_link');
        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['prev_link'] = '&laquo';            
        $config['prev_tag_open'] = '<li class="prev">';
        $config['prev_tag_close'] = '</li>';
        $config['next_link'] = '&raquo';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="page-item active"><a href="#" class="page-link">';
        $config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';

        Notes : 
        &laquo  means  << mark 
        &raquo  means  >> mark
        cur_tag means current tag
        num_tag means numbering tags

Now it comes the latter part of pagination function. 
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

$page is assigning to the URL format. Then what is the meaning of following line?
 ? $this->uri->segment(3) : 0;
This is same as a if else clause. It will be like this.
if (uri_segment(3)){
   uri_segment(3)
}else{
   0
}

If uri segment is 3(if there are 3 segments loaded in the URL), it will load the current segmented page. Otherwise it will load the first page as it has no 3 uri segments. Because it has no parameters and it is the page loaded by default. The URLs will be like this. 
First page : only 2 segments => Users/index
http://localhost/Projects/CIPagination/Users/index
Second page : 3 segments => Users/index/5
http://localhost/Projects/CIPagination/Users/index/5

Then we will continue the function.

$this->pagination->initialize($config); - Initialization of pagination

$data['link'] = $this->pagination->create_links();
Assign array to load data fetched. create_links() is a defined function.

$data['users'] = $this->User_model->getUserPagintaion($config['per_page'], $page);
Assign array to load records fetched from users table. getUserPagintaion is the model function we created for getting users per page. I passed two variables to that function. Here I assign values for those.]
$limit  =>  $config['per_page']  =>  5
$start  =>  $page  =>  zero for first page and other numbers for the other pages

$this->load->view('user_view', $data);  -  Load the view with the above data

Controller function is completed. Lets move to the view again and configure it to view records and pagination.

user_view full code :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CodeIgniter Pagination</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css">       
        <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">
        <style type="text/css">
            body {
                font-family: 'Source Sans Pro', sans-serif;
                font-size: 16px;
            }
            #wrapper {
                padding: 20px;
            }
        </style>
    </head>
  <body>


      <div id="wrapper">

        <h1>CodeIgniter Pagination</h1>
        <br>

        <div class="row">
            <div class="col-lg-12">
                <div class="table-responsive table-bordered">
                    <table class="table">

                    <tr>
                        <th>Index</th>
                        <th>Userame</th>
                        <th>Email</th>
                        <th>Change</th>
                        <th>Remove</th>
                    </tr>`

                    <?php if (count($users)): ?>

                    <?php foreach ($users as $row): ?>

                    <tr>
                        <td><?php echo $row->indexno; ?></td>
                        <td><?php echo $row->username; ?></td>
                        <td><?php echo $row->email; ?></td>
                        <td><a href="#"><button type='submit' class='btn btn-primary'>update</button></a></td>
                        <td><a href="#"><button type='submit' class='btn btn-danger'>Delete</button></a></td>

                    <?php endforeach; ?>

                    <?php else: ?>
                        <center><p style="margin: 20px;">No users registered</p></center>
                    <?php endif ?>
        
                    </table>
                </div>
                <br>
                <?php echo $link ?>  
            </div>
        </div>
        
        
          
        </div>

    <!-- JavaScript -->


    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="assets/js/bootstrap.min.js"></script>
  </body>
</html>

The records are include in a foreach loop. First check if there are results and then continue to display them. If there are no records,  it will display a text as "No Users Registered". I included users per page in $data['users'] within the controller. Here I have used it in foreach loop. Finally you have to include the pagination. Simply you have to include only one line.

<?php echo $link ?>  

I have included $data['link'] in the controller assigning the creation of links with the CI defined function create_links.

After you have done all these thing you are fully configured pagination for your project!  If you add more records to the database, CI will automatically format your records displaying 5 records per page. If you want more records per page, change the value.

This  is long tutorial. But nothing to do as this part is having a lot of new things. I have tried my best to shorten the article. Anyway I think you got the knowledge to add pagination to a CI project. If any questions, drop a comment.
Thank You!




Admin Semoga Informasi Yang Diberikan Melalui Web Ini Dapat Bermanfaat Bagi Saudara/i

No comments for "Pagination in CodeIgniter"