Over a million developers have joined DZone.

How to Paginate Search Results With CodeIgniter 2.1

DZone's Guide to

How to Paginate Search Results With CodeIgniter 2.1

· Web Dev Zone
Free Resource

Never build auth again! Okta makes it simple to implement authentication, authorization, MFA and more in minutes. Try the free developer API today! 

This article shows you how to go about paginating search results with CodeIgniter. The paginate library available in the CodeIgniter framework is very useful. It is also straightforward to implement. However, offering your users the ability to click through pages after a search needs a little more work.

This article is a follow up to my previous article I wrote for phpmaster.com that covers the basics of paginating with CodeIgniter. You should read that one first, if you haven’t already.

So, what we want to do is as follows: we have provided our users with a search form, so that they can search the world database we created in the basic pagination article.

The results of that search, might be small in number, but it might also produce a lot of records. Presenting the result set in a paginated list would therefore create a more Google-like experience for our users.

The problem is: because of the stateless nature of HTTP,  when the user clicks through the pagination links, the system will break because we will lose the search term that the user entered in the search box.

There is a solution though, so let’s see how we can paginate Search results with CodeIgniter 2.1.

Counting the records based on the user search term

We’ll start with the model. What we need is a way to count the number of records found for the users search. In the basic pagination example, getting a record count was easy. We used CodeIgniters ActiveRecord library count_all method to return the number of records in the database table.

That won’t do for our search results though. We need to count only the number of records the search query produces. That means we need a method parameter containing the search term from the form that the user submitted. Then we can use COUNT(*) to get the number of results.

Here is the method then, that needs to be added to the search_model.php file. that will achieve what we need:

public function search_record_count($searchterm)
    $sql = "SELECT COUNT(*) As cnt FROM Country
            WHERE Continent LIKE '%" . $searchterm . "%'";
    $q = $this->db->query($sql);
    $row = $q->row();
    return $row->cnt;

Here, you can see that we are passing in the search term the user entered (we’ll look at how we got that in a moment), and then we are using COUNT(*) to perform a query on the database table ‘Country’.

New Controller Method and the Search Term

In our controller welcome.php, we need to add a new method we’ll call search. In the method, we’ll grab the form value $_POST’ed from the search form:


public function search
    $searchterm = $this->input->post('searchterm',TRUE);

We are using CodeIgniters input class here, and it’s XSS filter, to make sure there is nothing nasty being entered into the search form.

Don’t forget to call the paginate library; either in the constructor method of welcome.php, or the search method:


The search method in the model

So the search method needs to carry out the search on the Country table based on the passed in search term. We also pass in the $limit value to establish where in the result set we should start from. You can read about the MySQL limit clause here.

Here is what it looks like:

public function search($searchterm,$limit)
    $sql = "SELECT * FROM Country
            WHERE Continent LIKE '%" . $searchterm . "%' LIMIT " .$limit . ",20";
    $q = $this->db->query($sql);
    if($q->num_rows() > 0)
        foreach($q->result() as $row)
            $data[] = $row;
        return $data;
        return 0;

This should be fairly self explanatory. Notice that we have set the number of results per page manually. That could also be a passed in parameter if we wished.

The Search View

We now need to create a new view called search.php. It can be pretty much identical to the other called example1.php. But we just need a search form to be included:

<form action ="<?=base_url()?>welcome/search" method="post" id="searchform">
    Search the database: 
    <input type="text" name="searchterm" id="searchterm" value="<?=$searchterm?>" /> 
    <input type="submit" value="Search >>" id="submit" />

Add the search form to the example1.php view too, so that you try a search from there. The form action should point to the search method in the welcome controller.

Try a search on a continent: (that is the way this example is set up. You could of course, change things to search on different values in the database).

Searching with CodeIgniter

You’ll see a set of results come back, and the will be a nice set of pagination links:

Searching with CodeIgniter

The problem will come when you click on the pagination links. You’ll notice that the query is no longer working. The displayed results will include everything in the table.

So what has gone wrong? The problem is, that http is a stateless protocol. That means it can’t keep hold of data between pages. As you click the links, the pages re-submit, and the search value is lost. We can fix that though.

Retaining the search value so that the Results Paginate

The solution is simple. We’ll employ CodeIgniters session library to keep hold of the search term until we are ready to destroy it.

One way to go about fixing the problem, is to write a handler method in our search_model. The purpose of the method, will be to check the various different states the $searchterm variable could be in. Lets have a look at the code:

public function searchterm_handler($searchterm)
        $this->session->set_userdata('searchterm', $searchterm);
        return $searchterm;
        $searchterm = $this->session->userdata('searchterm');
        return $searchterm;
        $searchterm ="";
        return $searchterm;

All we are doing here is: checking that the $searchterm variable is set (because the user submitted the search form), and assigning it to a session, returning the session variable if it is already set, or returning an empty string if nothing is set.

Now we can call this method in the search method of the welcome controller:


$searchterm =$this->search_model->searchterm_handler($this->input->get_post('searchterm', TRUE));

so that what ever state the $searchterm variable is in, it is now being tracked through our application. What that means, is the value the user originally typed will be held in the session variable. That will persist across pagination link clicks, therefore ensuring that our pagination now works correctly.

This assumes that you are autoloading the session library. If not, you’ll need to call it in the search method too.

Wrapping Up

There is one other thing we can do. Add the following code to the beginning of the example1 method in the welcome controller: $this->session->unset_userdata('searchterm'); This will make sure that the session variable gets reset when users start a new search.

So in this article you have seen how you can paginate database search results with CodeIgniter. You have seen how to ensure that the search value persists across page clicks, and how to calculate the number of records returned on the fly.

A fully working example is available on Github.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!


Published at DZone with permission of Andy Hawthorne, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}