CodeIgniter Pagination

Pagination refers to links that allows us to navigate from page to page.CodeIgniter's Pagination class is very easy to use and customizable.

<< First 2 3 4 Last >>

CodeIgniter Pagination Example

We will use following step to perform Pagination operation in CodeIgniter.

Step 1

First we create database and tables.

CREATE DATABASE pagination;
CREATE TABLE employee(
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `gender` char(20) DEFAULT NULL,
   PRIMARY KEY (`id`)
);
INSERT INTO `employee`(`id`,`name`,`gender`) VALUES (NULL,'Manish','Male');
INSERT INTO `employee`(`id`,`name`,`gender`) VALUES (NULL,'Pawan','Male');
INSERT INTO `employee`(`id`,`name`,`gender`) VALUES (NULL,'Kripal','Male');
INSERT INTO `employee` (`id`, `name`, `gender`) VALUES (NULL, 'Priya', 'Female');
INSERT INTO `employee` (`id`, `name`, `gender`) VALUES (NULL, 'Payal', 'Female');  
INSERT INTO `employee`(`id`,`name`,`gender`) VALUES (NULL,'Pradeep','Male'); 
INSERT INTO `employee`(`id`,`name`,`gender`) VALUES (NULL,'Punit','Male');  
Step 2

Create view files inside application\views\cipagination.php .

<html>
<head>
<title>Codeigniter Pagination Example  </title>
</head>
<body>
<h3>Codeigniter Pagination Example  </h3>
<?php
foreach($results as $data) {
 echo $data->name . " - " . $data->gender . "<br>";
}
?>
<p><?php echo $links; ?></p>
</body>
</html>
Step 3

Create Controller file inside application/controllers/cipagination.php .

<?php
class cipagination extends CI_Controller{

  function __construct()
{
parent::__construct();
$this->load->model("cipaginationmodel");
$this->load->library("pagination");
}
public function example() {
        $config = array();
        $config["base_url"] = base_url() . "cipagination/example";
        $config["total_rows"] = $this->cipaginationmodel->record_count();
        $config["per_page"] = 5;
        $config["uri_segment"] = 3;
 
        $this->pagination->initialize($config);
 
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data["results"] = $this->cipaginationmodel->fetch_employees($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();
 
        $this->load->view("cipagination", $data);
    }
}
?>
Step 4

Create Model files inside application/models/cipaginationmodel.php .

<?php
class cipaginationmodel extends CI_Model {
    function __construct()
    {
      parent::__construct();
    }
function record_count()
{
 return $this->db->count_all('employee');
}
public function fetch_employees($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get("employee");
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }

}
?>