Posted by Arjun on Wednesday 15th January 2014

Pagination with CodeIgniter ?

CodeIgniter How to Pagination

In this tutorial, We gonna use CodeIgniter built-in pagination library to show the paginated list of items on your web page.

pagination-codeigniter

Here are the steps to paginate in the CodeIgniter 3 application with CodeIgniter built-in pagination library:

Step 1: Download and install CodeIgniter.

Step 2: Create a database and create countries table with below SQl.

CREATE TABLE `countries` (
`id` int(11) NOT NULL auto_increment,
`country_code` varchar(2) NOT NULL default '',
`country_name` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- 
-- Dumping data for table `countries`
-- 
INSERT INTO `countries` VALUES (null, 'AF', 'Afghanistan');
INSERT INTO `countries` VALUES (null, 'AL', 'Albania');
INSERT INTO `countries` VALUES (null, 'DZ', 'Algeria');
INSERT INTO `countries` VALUES (null, 'DS', 'American Samoa');
INSERT INTO `countries` VALUES (null, 'AD', 'Andorra');
INSERT INTO `countries` VALUES (null, 'AO', 'Angola');
INSERT INTO `countries` VALUES (null, 'AI', 'Anguilla');
INSERT INTO `countries` VALUES (null, 'AQ', 'Antarctica');
INSERT INTO `countries` VALUES (null, 'AG', 'Antigua and Barbuda');
INSERT INTO `countries` VALUES (null, 'AR', 'Argentina');
INSERT INTO `countries` VALUES (null, 'AM', 'Armenia');
INSERT INTO `countries` VALUES (null, 'AW', 'Aruba');
INSERT INTO `countries` VALUES (null, 'AU', 'Australia');
INSERT INTO `countries` VALUES (null, 'AT', 'Austria');
INSERT INTO `countries` VALUES (null, 'AZ', 'Azerbaijan');
INSERT INTO `countries` VALUES (null, 'BS', 'Bahamas');
INSERT INTO `countries` VALUES (null, 'BH', 'Bahrain');

Step 3: Open your config/database.php file and configure your database connection settings, if you need more info please read How to connect to MySQL database in CodeIgniter?

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

Step 4: Create a model in the application which needs to do two things: Provide a count of all the records in the Country table, and retrieve a list of countries from the table. Create a file called Country_model.php at applications/models/ and copy below code to it.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class Country_model extends CI_Model
{
    private $table;
    
    public function __construct() {
        parent::__construct();
        $this->table = 'countries';
    }
 
    public function total_countries() {
        return $this->db->count_all($this->table);
    }
 
    public function get_countries($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get($this->table);
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;
   }
   
}
/* End of file country_model.php */
/* Location: ./application/models/country_model.php */

Step 5:
After creating Model, lets create a new controller called Country.php file in application/controllers folder.

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

class Country extends CI_Controller {

    function __construct() {
        parent::__construct();
        // load the database 
        $this->load->database();
        //load pagination library
        $this->load->library('pagination');
        //load post model
        $this->load->model('country_model');
        // load html and url helper
        $this->load->helper(array('url','html'));
    }
    
    public function index()
    {
        $total_rows = $this->country_model->total_countries();
        $config = $this->_pagination(base_url('country/index/'),$total_rows,5,3);
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $this->data['result'] = $this->country_model->get_countries($config['per_page'],$page);
        $this->load->view('country_view',$this->data);
    }
   
   private function _pagination($url,$total_rows,$per_page = 10,$uri_segment = FALSE) {
        $config['base_url'] = $url;
        $config['total_rows'] = $total_rows;
        $config['per_page'] = $per_page;
        if($uri_segment) {
          $config['uri_segment'] = $uri_segment;
        }
        $this->pagination->initialize($config);
        return $config;
   }
}

Step 6:
For the view file, Create a file called countries_view.php in applications/views/ folder.

<?php 
if(isset($result) && count($result) > 0) {
	foreach($result as $country) {
		$data[] = $country->name;
	}
	// ul() is html helper, it generate list items, it will take array as input
	echo ul($data);
	// display pagination links
	echo $this->pagination->create_links();
}

Hope this simple CodeIgniter pagination tutorial will help you in some aspect in the way to your CodeIgniter application development. Don’t hesitate to ask me if you have any question or issue in understanding the tutorial. Happy coding