Pagination with Code Igniter

10 comments | Posted: 12 February 07 in Tutorials, by Yannick Lyn Fatt

There are times when you may have to either split an article or a set of results lets say from a database query to span multiple pages. In times like those you will need to write some sort of pagination script. This can be a little overwhelming for developers who have never done something like that before, but with Code Igniter its a cinch to do.

Code Igniter comes with a Pagination class that is pretty easy to use and implement. In this tutorial I’ll do a quick example of returning a set of results from a database and paginating those results. I’ll be using the latest version of CI, which, as of this article is version 1.5.1. While the Pagination class hasn’t changed from the previous versions (at least not to my knowledge), it’s always good to use the latest stable version of the framework. So let’s get started.

Configuration and Database Setup

Okay, as usual, whenever we are starting a CI application, there are a few things we have to setup. First we open our config.php file (which can be found in /system/application/config/). Here we will enter our Base Site URL. This is what I set mine as:

$config['base_url'] = "http://localhost/~yannick/pagination/";

For you it will probably be something slightly different.

This application will be using a database, so our next step is to create that database and then give CI access to our database. To do this open database.php, which is also located in your config folder and put in the necessary information to connect to your database. You may download the “sample code”: for this tutorial and use my example database if you would like. It will create a table called ‘christian_books‘ and insert some test data to help with this tutorial. With that said I suppose you can now guess what we will be paginating. If you guessed some Christian Books then you would be correct.

The Controller

With our basic configuration files and database setup now complete we’ll need to create a controller. I will call mine ‘books.php‘ and it will contain the following code:

class Books extends Controller {
  function __construct() {
    parent::Controller();
    $this->load->helper('url');
    $this->load->database();
  }

  function index() {
    // load pagination class
    $this->load->library('pagination');
    $config['base_url'] = base_url().'index.php/books/index/';
    $config['total_rows'] = $this->db->count_all('christian_books');
    $config['per_page'] = '5';
    $config['full_tag_open'] = '<p>';
    $config['full_tag_close'] = '</p>';

    $this->pagination->initialize($config);
		
    //load the model and get results
    $this->load->model('books_model');
    $data['results'] = $this->books_model->get_books($config['per_page'],$this->uri->segment(3));
		
    // load the HTML Table Class
    $this->load->library('table');
    $this->table->set_heading('ID', 'Title', 'Author', 'Description');
		
    // load the view
    $this->load->view('books_view', $data);
  }
}

If you read through the Introduction to CI series I recently did then you may notice a few things here that are familiar. If you didn’t and are new to CI then feel free to go through that three part series and then return to this one. If you are already up to speed, then let us continue and have a look through the code above in more detail.

First we have our constructor in which we load our URL Helper and Database. Of course, you don’t have to create a constructor and load those helpers, as it you can easily load them in other the functions/methods in your controller, however, if the helpers are going to be used throughout most/all of the methods in the controller then I usually prefer to create a constructor and place them there.

Next we created one method called index(). This is a pretty basic application and as such we’ll only be needing this single method in which we loaded the pagination class, model and html table class (which we will discuss a little later in this tutorial).

Let us begin with the Pagination class, which, as you will see is very simple to use. First we configure the base URL of the web page to be paginated:

$config['base_url'] = base_url().'index.php/books/index/';

This base_url is not to be confused with the base_url() function I used in the assignment of the $config[] array. The base_url() function comes from the URL Helper and it represents the URL for the application on a whole. Concatenated to that is the remainder of the URL necessary to reference the web page to be paginated.

Next we configure the total number of rows in our database:

$config['total_rows'] = $this->db->count_all('christian_books');

Since I am returning all the rows in my database then this function will do fine, however, if you were running a specific query that will return some and not necessarily all the rows then you would probably want to use the $query->num_rows() function found in the set of result helper functions.

The $config['per_page'] variable simply tells the Pagination Class how many results to display on each page. And the $config['full_tag_open'] and $config['full_tag_close'] variables state what tags to use to surround the pagination links.

Next we load our model, which we will create shortly and execute one of its methods, get_books(). It takes in two arguments, the limit, which determines how many items to display on each page and an offset which will tell it what row to start returning results from. You will notice that the first argument (the limit) gets it’s value from the $config['per_page'] variable, while, the second argument gets its value from the 3rd segment of the URL via another URL helper function, $this->uri->segment(3). The latter is very interesting and here’s why. CI’s URLs usually take the following form, www.your-site.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://localhost/~yannick/pagination/index.php/books/index/10

The 3rd segment would be 10 and when inserted as the 2nd argument of our model function get_books(5, 10) it represents the offset. So in other words our results will return the next 5 records (since our results per page is 5, based on the code shown earlier) after the first 10 records in our database. Pretty neat, right? Okay, let’s stop here for now as we will talk about this in a little more detail the next section.

Now here’s something new. Here we are loading the HTML Table Class, which was a new addition to CI in Version 1.5.0. This class allows you to generate HTML tables from arrays or database results. There are quite a few customizations you can make, however for the purposes of this example I’m using it in it’s basic form with one exception, I’m specifying explicitly what the headings of the table should be.

$this->table->set_heading('ID', 'Title', 'Author', 'Description');

If I didn’t specify this, the HTML Table Class would use the table names as they are in the database table. So if for example you had a column name ‘book_id‘ in your database table, then the table class would use ‘book_id‘. Chances are, you don’t want it to be displayed like that, so the above snippet of code allows you to specify a more readable name for the column.

Lastly, we load our ‘View’ and pass it any necessary data that we will use. And there you have it, our controller is now done. Let us now take a look at our model and see what roll it plays in pagination.

The Model

Ok, so you may recall that the Model works with information in your database. In this Pagination tutorial our model will contain a method that deals with retrieving the correct results from our database based on the page that the user requested. As you saw in the controller the method will have two arguments, one for the limit and the other for the offset. So we create a file called ‘books_model.php‘ and the code in that file will be as follows:

class books_model extends Model {
  function __construct(){
    parent::Model();
  }

  function get_books($num, $offset) {
    $query = $this->db->get('christian_books', $num, $offset);	
    return $query;
  }
}

As you can see, we called our model ‘books_model‘ and our method get_books(), since this tutorial contains a database filled with books and we want to get those books and display them on screen. You will notice we called the two arguments to get_books(), $num and $offset respectively. $num specifies the number of results to retrieve from the database and $offset specifies where it should start retrieving results from.

$query = $this->db->get('christian_books', $num, $offset);

The above code will produce the following query in MySQL (for example):

SELECT * FROM christian_books LIMIT 10, 5

Five (5) represents $num and Ten (10) represents $offset. That’s all there is to it. We store those results in a variable called $query and then return that variable to anything that calls that method. And with that our model is now complete.

We are 2/3 of the way there. The last thing we need to do is to create our view.

The View

Remember a View is simply a web page or a page fragment. So our view in this case is a web page that displays our books in a table. Let’s have a look at the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href='<?php echo base_url(); ?>css/main.css' type="text/css" media="screen, projection" />
<title>CodeIgniter Pagination Tutorial</title>
</head>
<body>
<h1>Christian Books</h1>
<?php echo $this->table->generate($results); ?>
<?php echo $this->pagination->create_links(); ?>
</body>
</html>

You may be thinking, ‘Surely that can’t be it.’ Yeah that’s all there is to creating the view for this tutorial.

$this->table->generate($results);

By passing the results we obtained from our model to the generate() method it will create the HTML necessary to display our table containing our books.

$this->pagination->create_links();

Next we have our Pagination create_links() method, which does exactly what it says. It creates the links to the various pages including ‘Next’ and ‘Previous’ links. It will look a little something like this:

« First < 1 2 3 4 5 > Last »

Now visit your web page and have fun playing around with the Pagination. Also as you switch from page to page, watch how the URL changes and the 3rd segment represents the offset of the results displayed in the table.

Summary

Well there you have it, a quick introduction to the Pagination Class and as you have seen it’s not that difficult to add pagination to your application in CI. You were also introduced to the new HTML Table Class added in version 1.5.0. Again it wasn’t too difficult. With this Library we were able to whip up a quick HTML table to display our results.

Well that’s it for now, I hope you enjoyed this tutorial and found it informative and helpful. If you are interested in learning how to do Pagination in PHP without the help of the CI Framework, then I would recommend you watch Jonathan Sampson’s Pagination screencast.

Peace and God bless.

Download Code: ci_pagination_tut.zip

Discuss This Topic

  1. 1 Derek Allard

    Yannick. Super work! I hope you don’t mind, I’m going to take the liberty of posting this to the CI forums.

    And source-code to boot. Nice!

     
  2. 2 Yannick

    Thanks Derek. I don’t mind at all. As long as this helps someone to learn to use CI then it’s fine by me. :)

     
  3. 3 Yannis

    Thanks Yannick, your super tutorials have convinced me to use CI for my web project.

    I’ve gone thru your pagination tutorial with the books and pagination links being displayed ok but when I click on a link i get ‘page not found’. When this happens the url changes to this “http://localhost/guestbook/;/index.php/books/index/5”. Any ideas?

     
  4. 4 Yannick

    Hey Yannis,

    Awesome that you decided to use CI for your web project. When you’re done I’d love to see it.

    Regarding your page not found error. I’m looking at the url you said displayed and I noticed there is a semicolon (;) between the trailing slash after guestbook and the on one just before index.php. You might want to check either the $config[‘base_url’] variable in config.php or check the URL again in the $config[‘base_url’] in your controller for the pagination as the Semicolon shouldn’t be there in the URL you specified.

    Hope that helps. If not, then let me know and we can troubleshoot further.

    Off Topic: By the way, cool name. Change that ‘s’ to ‘ck’ and you’ve got my name. :)

     
  5. 5 Boris

    Simply awesome. Thanks.

     
  6. 6 Yannick

    You’re welcome Boris. Glad you thought it was ‘awesome’. :)

     
  7. 7 esra

    Yannick… nice work and very much appreciated—direct, concise and right to the point. I’m putting a copy in my treasure chest.

     
  8. 8 Yannick

    Esra: You are most welcome. I’m happy you found the article helpful. If there is anything you would like to see covered in future tutorials then don’t hesitate to let me know. You can email us via the Godbit contact form with your suggestions.

     
  9. 9 Flosaurus

    Awesome tutorial and also well explained !!!

    I was wondering whether you would like to update this tutorial with an ajax pagination…

    Thanks anyway !

     
  10. 10 Yannick

    Flosaurus: While I’ve never played with AJAX before, I suppose I could give it a try. When I get some time I’ll have a go and will make a post about it.

     

Comments closed after 2 weeks.