Pagination Using Php Codeigniter

Pagination Using Php Codeigniter

By Yashwant Chavan, Views 28153, Date 21-Nov-2014

This tutorial will introduce you to codeigniter pagination concept. What you will find in this tutorial is that codeigniter pagination encompasses many areas , including pagination configuration , pagination controller , pagination model and pagination view page. With the help of this example you can easily learn codeigniter pagination concept.

tags php php-codeigniter pagination

In the real world scenario, most of time we have to display large number of records from database table and its not good programming practice to display all the records in one fetch. To avoid this you can divide your result set into number pages base on configuration. So that user can easily navigate through result set with the help of pagination links.

Popular Codeigniter Tutorials

Tools and Technologies

I am using below tools and technologies to implement pagination.

  1. Php Codeigniter 1.7.3
  2. XAMPP / Php 5.2.3
  3. Mysql 5.0.4

Database table trn_movies

Create trn_movies table with the help of below mysql table script. Once you are done with the table creation in mysql database, Our next step is to set up php Codeigniter project.

 CREATE TABLE  `technicalkeeda`.`trn_movies` (
   `movie_id` int(10) unsigned NOT NULL auto_increment,
   `film_name` varchar(45) collate latin1_general_ci NOT NULL,
   `director` varchar(45) collate latin1_general_ci NOT NULL,
   `release_year` int(10) unsigned NOT NULL,
   PRIMARY KEY  (`movie_id`)
 );

Insert few records in trn_movies table. Use below script to insert some of the movie names

 INSERT INTO `trn_movies` (`movie_id`,`film_name`,`director`,`release_year`) VALUES 
 (1,'Happy New Year','Farah Khan',2014),
 (2,'Kill Dil','Shaad Ali',2014),
 (3,'The Shaukeens','Abhishek Sharma',2014),
 (4,'Kick','Sajid Nadiadwala',2014),
 (5,'Bang Bang','Siddharth Anand',2014),
 (6,'Ungli','Rensil DSilva',2014),
 (7,'Happy Ending',' Krishna D.K',2014),
 (8,'Jai Ho','Sohail Khan',2014),
 (9,'Lingaa','K. S. Ravikumar',2015),
 (10,'Daawat-e-Ishq','Habib Faisal',2014),
 (11,'Singham Returns','Rohit Shetty',2014);

I am using Codeigniter Version # 1.7.3 to develop the this application, You can use the latest version also. Simple Codeigniter application project looks like below in Eclipse editor.

codeigniter pagination project setup

Codeigniter Database Configuration

As you know that Php Codeigniter is popular for minimum configuration (almost Zero configuration) framework. To connect to database you need to provide username, password and database name configuration details in database.php file.

The config file is located at "application/config/database.php". Like in my case my local mysql database setting is as below.

 $db['default']['hostname'] = "localhost";
 $db['default']['username'] = "root";
 $db['default']['password'] = "";
 $db['default']['database'] = "technicalkeeda";

Codeigniter Base Url Configuration

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

Pagination Configuration and Customization

First you have to load the pagination library before using its any method.

$this->load->library('pagination');

Codeigniter pagination library is 100% customizable, you change the configuration as per your need, In below example I have did some customization, Its hard to me, to go through each and every configuration but I will cover some of them.

$config['per_page'] = 5; - Display number of records per page

$config['uri_segment'] = '2'; - The pagination function automatically determines which segment of your URI contains the page number. As per your logic you specific the segment number , where your page number available

$config['full_tag_open']... - If you would like to add container to the entire pagination with some mark up tags then you use this option. Here I am using bootstrap pagination <div class="pagination"><ul> component. For other customization you can refer the CodeIgniters Pagination official website.

Once you are done with the customization then you need to initialize the pagination library.

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

Pagination Controller (home.php)

Lets creates the Controller class called Home under folder name application/controllers along with default method name index().

<?php
class Home extends Controller {

 function Home(){
  parent::Controller();
  $this->load->model('MovieModel');
  $this->load->library('pagination');
 }
 public function index($offset=0){
  
  $config['total_rows'] = $this->MovieModel->totalMovies();
  
  $config['base_url'] = base_url()."index.php/home";
  $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);
   

  $query = $this->MovieModel->getMovies(5,$this->uri->segment(2));
  
  $data['MOVIES'] = null;
  
  if($query){
   $data['MOVIES'] =  $query;
  }

  $this->load->view('index.php', $data);
 }
}
?>

Pagination Model (MovieModel.php)

Lets create the Model class which will query the database table and fetch the records. Navigate to the application/models folder of your codeigniter project and create a new php file called MovieModel.php

The totalMovies() method returns total number of records available in the trn_movies table and which will used to set $config['total_rows'] configuration option.

And another method is used to return the records base on $limit and $offse parameters which is used to determine how many records to fetch , and what record to start from.

<?php
class MovieModel extends Model {

 function MovieModel(){
  parent::Model();
 }

 function getMovies($limit=null,$offset=NULL){
  $this->db->select("MOVIE_ID,FILM_NAME,DIRECTOR,RELEASE_YEAR");
  $this->db->from('trn_movies');
  $this->db->limit($limit, $offset);
  $query = $this->db->get();
  return $query->result();
 }

 function totalMovies(){
  return $this->db->count_all_results('trn_movies');
 }
}
?>

index.php

Lets create index.php file under folder name application/views. Here we are going to display the movie records. Add below code to creat the pager links in your view page <?php echo $this->pagination->create_links(); ?>

 <!DOCTYPE html>
 <html lang="en">
  <head>
   <title>Codeigniter Pagination Example</title>
   <link href="<?= base_url();?>css/bootstrap.css" rel="stylesheet">
  </head>
  <body>
   <div class="container">
    <div class="row">
     <div class="col-md-12">
      <div class="row">
      
       <h4>Movies List</h4>
       <table class="table table-striped table-bordered table-condensed">
        <tr><td><strong>Movie Id</strong></td><td><strong>Film Name</strong></td><td><strong>Director</strong></td><td><strong>Release Year</strong></td></tr> 
        <?php 
        if(is_array($MOVIES) && count($MOVIES) ) {
         foreach($MOVIES as $movie){     
        ?>
        <tr><td><?=$movie->MOVIE_ID;?></td><td><?=$movie->FILM_NAME;?></td><td><?=$movie->DIRECTOR;?></td><td><?=$movie->RELEASE_YEAR;?></td></tr>     
           <?php 
         }        
        }?>  
       </table>            
      </div>
     </div>
    </div>
    <div class="row">
              <div class="col-md-12">
      <div class="row"><?php echo $this->pagination->create_links(); ?></div> 
     </div>
    </div>
   </div>    
  </body>
 </html> 

Run

Enter the url http://localhost/codeigniterdemo/index.php/home in your browser, It will display the result in pagination format, Refer below images.

Codeigniter Pagination Example Screen Shot 1

Move to Next page with the help of Pagination URLS

Codeigniter Pagination Example Screen Shot 2
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]