how to do pagination using codeigniter

Pagination is the most required feature in the web application. Generally, pagination is useful when data is retrieved from the database and listed in the web page. Pagination in data list is mandatory when you need to list the huge data. It helps to load data faster and make your web application user-friendly.

If your web application built with CodeIgniter framework, it’s very easy to implement pagination in the data list. CodeIgniter provides Pagination class to create pagination links for the results set. In this tutorial, we will provide a step-by-step guide to implement pagination in CodeIgniter using Pagination library.

For the example purpose, we will fetch the posts data from the database and list this records with pagination link. The following functionality will be implemented to demonstrate CodeIgniter pagination.

  • Retrieve data from the MySQL database
  • Create pagination links using Pagination library.
  • List records with pagination links.

Create Database Table

The posts table contains some basic fields to store the post data.

1
2
3
4
5
6
7
CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `content` text COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Controller (Posts.php)

The Posts controller consists of 2 methods, __construct() and index().
__construct()

  • Load Pagination library.
  • Load Post model.
  • Specify pagination limit (per page).

index()

  • Get total rows count using getRows() method of Post model.
  • Specify the configuration in $config array for Pagination class.
  • Initialize the Pagination class with your preferred options using initialize() method.
  • Define offset by the page URI.
  • Get rows from posts table using getRows() method of Post model.
  • Pass the posts data to view and load the list view.

Some configuration options are specified for styling the pagination links with Bootstrap. You can omit this configuration (styling) if want to use basic style.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Posts extends CI_Controller {
   
    function __construct() {
        parent::__construct();
        //load pagination library
        $this->load->library('pagination');
        //load post model
        $this->load->model('post');
        //per page limit
        $this->perPage = 4;
    }
   
    public function index(){
        $data = array();
       
        //get rows count
        $conditions['returnType'] = 'count';
        $totalRec = $this->post->getRows($conditions);
       
        //pagination config
        $config['base_url']    = base_url().'posts/index/';
        $config['uri_segment'] = 3;
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
       
        //styling
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="active"><a href="javascript:void(0);">';
        $config['cur_tag_close'] = '</a></li>';
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Prev';
        $config['next_tag_open'] = '<li class="pg-next">';
        $config['next_tag_close'] = '</li>';
        $config['prev_tag_open'] = '<li class="pg-prev">';
        $config['prev_tag_close'] = '</li>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
       
        //initialize pagination library
        $this->pagination->initialize($config);
       
        //define offset
        $page = $this->uri->segment(3);
        $offset = !$page?0:$page;
       
        //get rows
        $conditions['returnType'] = '';
        $conditions['start'] = $offset;
        $conditions['limit'] = $this->perPage;
        $data['posts'] = $this->post->getRows($conditions);
       
        //load the list page view
        $this->load->view('posts/index', $data);
    }
   
}

Model (Post.php)

READ  How to Generate SEO Friendly URL in CodeIgniter

The Post model is used to retrieve posts data from the database. The getRows() function fetch the records from posts table based on the limit restriction provided in the $params array and returns posts data as an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends CI_Model{
    /*
     * Get posts
     */
    function getRows($params = array()){
        $this->db->select('*');
        $this->db->from('posts');
        if(array_key_exists("id",$params)){
            $this->db->where('id',$params['id']);
            $query = $this->db->get();
            $result = $query->row_array();
        }else{
            //set start and limit
            if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
                $this->db->limit($params['limit'],$params['start']);
            }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
                $this->db->limit($params['limit']);
            }
           
            if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
                $result = $this->db->count_all_results();
            }else{
                $query = $this->db->get();
                $result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }

        //return fetched data
        return $result;
    }
}

View (posts/)

READ  Hooks concept in codeigniter with simple examples?

The view folder (posts/) contains index.php file to list the paginated data.

index.php
The bootstrap library is used for styling the posts lists and pagination links. So, include the Bootstrap library first. If you want to use basic style, don’t need to include it.

1
link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

In index.php file, the posts data are listed with the pagination links. The create_links() function of Pagination class generates the pagination links.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<div class="panel panel-default ">
    <div class="panel-heading">Posts </div>
    <div class="panel-body">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th width="5%">ID</th>
                    <th width="30%">Title</th>
                    <th width="65%">Content</th>
                </tr>
            </thead>
            <tbody id="userData">
                <?php if(!empty($posts)): foreach($posts as $post): ?>
                <tr>
                    <td><?php echo '#'.$post['id']; ?></td>
                    <td><?php echo $post['title']; ?></td>
                    <td><?php echo (strlen($post['content'])>150)?substr($post['content'],0,150).'...':$post['content']; ?></td>
                </tr>
                <?php endforeach; else: ?>
                <tr><td colspan="3">Post(s) not found......</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<!-- render pagination links -->
<ul class="pagination pull-right">
    <?php echo $this->pagination->create_links(); ?>
</ul>