IMG-LOGO
Home Tutorial Codeigniter Pagination

Codeigniter Pagination

by MH RISHAD - 09 Dec 2018
IMG

If you are not familiar with the term “pagination”, it refers to links that allows you to navigate from page to page, like this:

« First  < 1 2 3 4 5 >  Last »

Example

Here is a simple example showing how to create pagination in one of your controller methods:

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

$config['base_url'] = 'http://example.com/index.php/test/page/';
$config['total_rows'] = 200;
$config['per_page'] = 20;

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

echo $this->pagination->create_links();

Notes

The $config array contains your configuration variables. It is passed to the $this->pagination->initialize() method as shown above. Although there are some twenty items you can configure, at minimum you need the three shown. Here is a description of what those items represent:

  • base_url This is the full URL to the controller class/function containing your pagination. In the example above, it is pointing to a controller called “Test” and a function called “page”. Keep in mind that you can re-route your URI if you need a different structure.
  • total_rows This number represents the total rows in the result set you are creating pagination for. Typically this number will be the total rows that your database query returned.
  • per_page The number of items you intend to show per page. In the above example, you would be showing 20 items per page.

The create_links() method returns an empty string when there is no pagination to show.

Setting preferences in a config file

If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called pagination.php, add the $config array in that file. Then save the file in application/config/pagination.php and it will be used automatically. You will NOT 

 need to use $this->pagination->initialize() if you save your preferences in a config file.

Customizing the Pagination

The following is a list of all the preferences you can pass to the initialization function to tailor the display.

$config[‘uri_segment’] = 3;

The pagination function automatically determines which segment of your URI contains the page number. If you need something different you can specify it.

$config[‘num_links’] = 2;

The number of “digit” links you would like before and after the selected page number. For example, the number 2 will place two digits on either side, as in the example links at the very top of this page.

$config[‘use_page_numbers’] = TRUE;

By default, the URI segment will use the starting index for the items you are paginating. If you prefer to show the the actual page number, set this to TRUE.

$config[‘page_query_string’] = TRUE;

By default, the pagination library assume you are using URI Segments, and constructs your links something like:

http://example.com/index.php/test/page/20

If you have $config['enable_query_strings'] set to TRUE your links will automatically be re-written using Query Strings. This option can also be explicitly set. Using $config['page_query_string'] set to TRUE, the pagination link will become:

http://example.com/index.php?c=test&m=page&per_page=20

Note that “per_page” is the default query string passed, however can be configured using $config['query_string_segment'] = 'your_string'

$config[‘reuse_query_string’] = FALSE;

By default your Query String arguments (nothing to do with other query string options) will be ignored. Setting this config to TRUE will add existing query string arguments back into the URL after the URI segment and before the suffix.:

http://example.com/index.php/test/page/20?query=search%term

This helps you mix together normal URI Segments as well as query string arguments, which until 3.0 was not possible.

$config[‘prefix’] = ‘’;

A custom prefix added to the path. The prefix value will be right before the offset segment.

$config[‘suffix’] = ‘’;

A custom suffix added to the path. The suffix value will be right after the offset segment.

$config[‘use_global_url_suffix’] = FALSE;

When set to TRUE, it will override the $config['suffix'] value and instead set it to the one that you have in $config['url_suffix'] in your application/config/config.php file.

Adding Enclosing Markup

If you would like to surround the entire pagination with some markup you can do it with these two preferences:

$config[‘full_tag_open’] = ‘<p>’;

The opening tag placed on the left side of the entire result.

$config[‘full_tag_close’] = ‘</p>’;

The closing tag placed on the right side of the entire result.

Customizing the First Link

$config[‘first_link’] = ‘First’;

The text you would like shown in the “first” link on the left. If you do not want this link rendered, you can set its value to FALSE.

Note

This value can also be translated via a language file.

$config[‘first_tag_open’] = ‘<div>’;

The opening tag for the “first” link.

$config[‘first_tag_close’] = ‘</div>’;

The closing tag for the “first” link.

$config[‘first_url’] = ‘’;

An alternative URL to use for the “first page” link.

Customizing the Last Link

$config[‘last_link’] = ‘Last’;

The text you would like shown in the “last” link on the right. If you do not want this link rendered, you can set its value to FALSE.

Note

This value can also be translated via a language file.

$config[‘last_tag_open’] = ‘<div>’;

The opening tag for the “last” link.

$config[‘last_tag_close’] = ‘</div>’;

The closing tag for the “last” link.

Customizing the “Next” Link

$config[‘next_link’] = ‘&gt;’;

The text you would like shown in the “next” page link. If you do not want this link rendered, you can set its value to FALSE.

Note

This value can also be translated via a language file.

$config[‘next_tag_open’] = ‘<div>’;

The opening tag for the “next” link.

$config[‘next_tag_close’] = ‘</div>’;

The closing tag for the “next” link.

Customizing the “Previous” Link

$config[‘prev_link’] = ‘&lt;’;

The text you would like shown in the “previous” page link. If you do not want this link rendered, you can set its value to FALSE.

Note

This value can also be translated via a language file.

$config[‘prev_tag_open’] = ‘<div>’;

The opening tag for the “previous” link.

$config[‘prev_tag_close’] = ‘</div>’;

The closing tag for the “previous” link.

Customizing the “Current Page” Link

$config[‘cur_tag_open’] = ‘<b>’;

The opening tag for the “current” link.

$config[‘cur_tag_close’] = ‘</b>’;

The closing tag for the “current” link.

Customizing the “Digit” Link

$config[‘num_tag_open’] = ‘<div>’;

The opening tag for the “digit” link.

$config[‘num_tag_close’] = ‘</div>’;

The closing tag for the “digit” link.

Hiding the Pages

If you wanted to not list the specific pages (for example, you only want “next” and “previous” links), you can suppress their rendering by adding:

$config['display_pages'] = FALSE;

Adding attributes to anchors

If you want to add an extra attribute to be added to every link rendered by the pagination class, you can set them as key/value pairs in the “attributes” config:

// Produces: class="myclass"
$config['attributes'] = array('class' => 'myclass');

Note

Usage of the old method of setting classes via “anchor_class” is deprecated.

Disabling the “rel” attribute

By default the rel attribute is dynamically generated and appended to the appropriate anchors. If for some reason you want to turn it off, you can pass boolean FALSE as a regular attribute

$config['attributes']['rel'] = FALSE;

Class Reference

classCI_Pagination

initialize([$params = array()])

Parameters:
  • $params (array) – Configuration parameters
Returns:

CI_Pagination instance (method chaining)

Return type:

CI_Pagination

Initializes the Pagination class with your preferred options.

create_links()

Returns: HTML-formatted pagination
Return type:

string

Returns a “pagination” bar, containing the generated links or an empty string if there’s just a single page.

 

Some Code Are ..... Example :

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.

<?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)

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.

<?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/)

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.

<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.

<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>
Share:

Leave a Comment

Required fields are marked *