Pages

Codeigniter Pagination

Sunday, February 26, 2012
This tutorial is part 2 of the tutorial series Building Website with CI.

In this part 2 will explain you about Codeigniter Pagination Class.

What is Pagination?

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


We crated a site like facebook in the part 1 (How to start with CI?). In this part we will add the pagination to our site.

Controller

I added some chunk of code to our controller index function like following.

public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->model("message_model");

        $total=$this->message_model->message_count();
        $per_pg=5;
        $offset=$this->uri->segment(3);

        $this->load->library('pagination');
        $config['base_url'] = $data['base'].'/index.php/home/index/';
        $config['total_rows'] = $total;
        $config['per_page'] = $per_pg;
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';

        $this->pagination->initialize($config);
        $data['pagination']=$this->pagination->create_links();

        $data['query']=$this->message_model->get_all($per_pg,$offset);
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }

Don't worry if you don't understand above code. I will explain you.

The first line I have added is

$total=$this->message_model->message_count();

This line will grab the total number of rows from our database table. To get the total number of rows, we have to add the message_count() function to our message_model model. I will show you writing message_count() function in our model section. Now we have got the total number of rows from our database table.

Next we create a variable $per_pg for our pagination class. This variable is to adjust how many rows to display in each page.

Next we read the value of the third segment of the URI which is the current offset number to a variable called $offset. If the segment is empty the we set the value as 0.

Here we need to understand about CI URLs structure. CI’s URLs usually take the following form,

www.examlple.com/index.php/class/function/ID,

so as you can see the 3rd segment (after index.php) represents the ID. So lets take for example the following URL:

http://www.example.com/index.php/home/index/5

The ID number will depend on our $per_pg ( per page) variable. If we set the per page as 5, our ID number will go 5,10,15,... If we set the per page as 10, our ID number will go 10,20,30,... So this is offset value for our database query.

Next we load the pagination library. It is required if you will be accessing any of its methods.

Next we need to set the values to config our pagination.
$config['base_url'] = $data['base'].'/index.php/home/index/';
First one is base_url that the base URL of the web page to be paginated. Base URL from config file and concatenated to that is the remainder of the URL necessary to reference the web page to be paginated.
$config['total_rows'] = $total;
We have already got this variable as $total. So set it up.
$config['per_page'] = $per_pg;
We have already created this one first so set it up.
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';

Above two lines are for our pagination design. First one will appear before the pagination link and second one will appear after the pagination link.

$this->pagination->initialize($config);
$data['pagination']=$this->pagination->create_links();
In above two lines, first one is initialize our pagination class. Second one is create a link and return the value and set it to our $data variable array as pagination variable. We will use this variable in our view file.

In part 1 of our controller, we grab all data from our database like this:

$data['query']=$this->message_model->get_all();

To add the pagination, we need to pay the limit and offset as the parameters for our database query.

Limit determine how many rows we want to grab from our database table or how many rows to display in each page and offset which will it what row to start returning results from.

So our code will be look like this
$data['query']=$this->message_model->get_all($per_pg,$offset);
Rest of our code is like part 1.

Model

I rewrote the get_all() function and added message_count() function to count the total rows from our message table like following.

public function get_all($per_pg,$offset)
    {
 $this->db->order_by('id','desc');
        $query=$this->db->get('message',$per_pg,$offset);
        return $query->result();
    }
    public function message_count()
    {
        return $this->db->count_all('message');
    }

As you saw in the controller the method will have two arguments, one for the limit or per page and the other for the offset. So you will notice we called the two arguments to get_all(), $per_pg and $offset respectively. $per_pg specifies the number of results to retrieve from the database and $offset specifies where it should start retrieving results from.
$this->db->order_by('id','desc');
The above code will produce the following query in MySQL:
ORDER BY id DES
$this->db->get('message',$per_pg,$offset);
The above code will produce the following query in MySQL:
SELECT * FROM message LIMIT 5, 0

So because of these two lines, query in MySQL will be: SELECT * FROM message ORDER BY id DESC LIMIT 5, 0

And then I will explain you about message_count() function.
public function message_count()
{
     return $this->db->count_all('message');
}
It is so clear. It will return the number of rows in a particular table as an integer. Submit the table name in the parameter.

View

In view file, we only need to do is echoing our pagination variable in a rightful place. So we have to add below code after the foreach loop in our messageform_view view file.

echo $pagination;

Styling with css

We should add some style to our style.css for our pagination. We wrapped the pagination with div id named pagination in our controller. So add below css code to our style.css.

#pagination{
    float: left;
    font:11px Tahoma, Verdana, Arial, "Trebuchet MS", Helvetica, sans-serif;
    color:#3d3d3d;
    margin-top: 20px;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:20px;
    width:100%;
}
#pagination a, #pagination strong{
    list-style-type: none;
    display: inline;
    padding: 5px 8px;
    text-decoration: none; 
    background-color: inherit;
    color: #EC7117;
    font-weight: bold;
}
#pagination strong{
    color: #ffffff;
    background-color:#F00;
    background-position: top center;
    background-repeat: no-repeat;
    text-decoration: none; 
}
#pagination a:hover{
    color: #ffffff;
    background-color:#F00;
    background-position: top center;
    background-repeat: no-repeat;
    text-decoration: none; 
}

Now you can run your site. Next tutorial we will do the form validation with CI.
Download Source Code

12 comments:

  1. GOD bless you .. you are a life saver

    ReplyDelete
  2. excellent..
    exactly what i'm looking for..
    thanx for sharing...

    ReplyDelete
  3. Thanks for posting its working great..

    ReplyDelete
  4. Nice Post it help me lot to perform CodeIgniter Pagination, I have got anoter basic implementation of CodeIgniter Pagination from http://www.tutsway.com/cipagination.php

    ReplyDelete
  5. what happens when page number goes out of 20 its not perfect for long database

    ReplyDelete
  6. Pagination in codeigniter can be created without creating mysql database first. Just create model controller and view and get on with it. Like done here: https://www.cloudways.com/blog/pagination-in-codeigniter/

    ReplyDelete
  7. Thanks for sharing the information. It is very useful for my future. keep sharing.

    Best Linux training in Noida
    Linux Training Institute in Noida

    ReplyDelete
  8. Superb blog I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and justifiable. The substance of data is exceptionally instructive.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training

    ReplyDelete