Search

Pagination in CodeIgniter 3.1.11 with Step by Step Example

  • Share this:
post-title

When you perform a search on your web portal , the results are displayed in a list and you have the options to click through pages of the results. That is an example of pagination. pagination simply means the user has the ability to click through the pages of results, viewing a subset of them each time, farther than having to scroll down the screen for pages.

In this tutorial, I’ll use CodeIgniter 3.1.11 pagination library to show you how you can create a paginated list of number results from a MySQL database. Along the way, you’ll also see how to fix a problem with the pagination links that the library might produce.
I’ll assume you have an installation of CodeIgniter 3.1.11 ready to go. For the database, I’ll use the official sample database provided by MySQL that available for download as an CodeIgniter 3.1.11 pagination mini project with SQL file updated code . 

The create model

We'll start by creating a model in the pagination application which needs to do two things : provide a count of all the records in the user table, and retrieve a list of user from the table. Save the following as models/base_model.php:

<?php 
class bace_model extends CI_Model{ 
	function __construct(){ 
		parent::__construct(); 
	} 
	public function record_count($tbl) { 
		return $this->db->count_all($tbl); 
	} 
	//for general database query 
	public function run_query($query){ 
		return $this->db->query($query); 
	} 
}

CodeIgniter database class with Active Records is used to count and retrieve the data from the database user table.

The controller

we need to create a method in the default Welcome controller (controllers/welcome.php) called index(). But just before we do that, we’ll need to load the model and also the pagination library in the class ’ constructor function.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper("url");
        $this->load->model("bace_model");
        $this->load->library('pagination');
    }
    public function index()
    {
        $config['base_url']        = base_url();
        $config['total_rows']      = $this->bace_model->record_count('user');
        $config['per_page']        = 10;
        $config["full_tag_open"]   = '<ul class="pagination">';
        $config["full_tag_close"]  = '</ul>';
        $config["first_tag_open"]  = '<li class="page-item page-link">';
        $config["first_tag_close"] = '</li>';
        $config["last_tag_open"]   = '<li class="page-item page-link">';
        $config["last_tag_close"]  = '</li>';
        $config["next_tag_open"]   = '<li class="page-item"><span aria-hidden="true">';
        $config["next_tag_close"]  = '</span></li>';
        $config["prev_tag_open"]   = '<li class="page-item"> <span aria-hidden="true">';
        $config["prev_tag_close"]  = '</span></li>';
        $config["num_tag_open"]    = '<li class="page-item ">';
        $config["num_tag_close"]   = '</li>';
        $config["cur_tag_open"]    = '<li class="page-item active"> <a>';
        $config["cur_tag_close"]   = '</a></li>';
        $config['first_link']      = "Previous";
        $config['last_link']       = "Next";
        $this->pagination->initialize($config);
        $limitstart                    = $this->uri->segment(1) ? $this->uri->segment(1) : 0;
        $this->data["paginetionlinks"] = $this->pagination->create_links();
        $this->data["returndata"]      = $this->bace_model->run_query("select * from user limit " . $limitstart . "," . $config['per_page'] . " ");
        $this->load->view('pagination', $this->data);
    }
}

The view

Finally, let's create a view file at views/pagination.php that displays the user listing.

<html>
    <head>
        <title>Paging Example-User Records</title>
    </head>
    <body>
        <div class="container">
            <h1 id='form_head'>User Records</h1>
            <?php if (isset($results)) { ?>
                <table border="1" cellpadding="0" cellspacing="0">
                    <tr>
                        <th>ID</th>
                        <th>NAME</th>
                    </tr>
                    <?php foreach ($results as $data) { ?>
                        <tr>
                            <td><?php echo $data->user_id ?></td>
                            <td><?php echo $data->user_name ?></td>
                        </tr>
                    <?php } ?>
                </table>
            <?php } else { ?>
                <div>No user(s) found.</div>
            <?php } ?>
 
            <?php if (isset($paginetionlinks)) { ?>
                <?php echo $paginetionlinks ?>
            <?php } ?>
        </div>
    </body>
</html>

Next step ' So now when you visit http://yourdomain/welcome/  you should see something like this :

initialization config variable

The $config array contains your all 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:

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

base_url() This method is the full URL to the controller class/function containing your pagination. In the example above, it is pointing to a controller called “Welcome” and a function called “index”. Keep in mind that you can re-route your URI if you need a different structure.

$config['base_url'] = base_url();

total_rows() This method is 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.

$config['total_rows'] = $this->bace_model->record_count('user');

per_page() This method is the number of items you intend to show per page. In the above example, you would be showing 10 items per page.

$config['per_page'] = 10;

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

$this->data["paginetionlinks"] = $this->pagination->create_links();

Let's go through the record_count method. It's used to count the number of records in the users table.

public function record_count($tbl) { 
	return $this->db->count_all($tbl); 
}

Next, there's a run_query method.

//for general database query 
public function run_query($query){ 
	return $this->db->query($query); 
} 
//for general database query 
$this->bace_model->run_query("select * from user limit " . $limitstart . "," . $config['per_page'] . " ");

There are two important variable that you should note in the run_query method. The first variable, $limitstart , is used to specify the number of records that will be returned during the query run. And the second variable, $config['per_page'], acts as the starting index of the record.

In order to use pagination in CodeIgniter, the first thing you need to do is to load the pagination library. And we can do it by using $this->load->library('pagination').

We've also loaded the URL helper so that we can use global helper functions provided by that helper.

Now, we're ready to go through the heart of our controller—the __construct method.
$this->load->helper("url");
$this->load->model("bace_model");
$this->load->library('pagination');

Explore Customization Options

In this section, we'll explore the options available that you could use should you wish to customize the default pagination links.

URI Segment

Although the CodeIgniter paging library automatically detects the paging-related parameter from the URL, you could define a custom value if you have different URL pattern.

$config["uri_segment"] = 4;

Number of Digit Links

The num_links option allows you to define the number of digit links that will be displayed before and after the active page number in the pagination links.

$config['num_links'] = 2;

Page Number as URI Segment

When you access the paging URI segment, it's a starting index by default. For example, if you have ten records per page, the paging URI segment is 20 for the third page. Instead, if you want to show actual page numbers in the paging links, you can set use_page_numbers to TRUE.

$config['use_page_numbers'] = TRUE;

Preserve Query String

More often than not, you end up in the situation where you want to preserve query string parameters that are not related to pagination. You can use the reuse_query_string option to enable that facility.

$config['reuse_query_string'] = TRUE;

Wrapper Tag

If you want to wrap the pagination code with any other HTML tag and css desing then you could do it using the full_tag_open and full_tag_close options.

$config['full_tag_open'] = '<div class="pagination">';
$config['full_tag_close'] = '</div>';

It could be really useful should you wish to apply custom styling to the pagination links.

First, Last, Next, and Previous

If you want to change the text that will be displayed for the first, last, next and previous links, you could do that as well.

$config['first_link'] = 'First Page';
$config['last_link'] = 'Last Page';
$config['next_link'] = 'Next Page';
$config['prev_link'] = 'Prev Page';

Also, if you want to wrap those individual links with any HTML tag with desin full , you could do that in the same way as we did it to wrap the whole paging code.

$config["first_tag_open"]  = '<li class="page-item page-link">';
$config["first_tag_close"] = '</li>';
$config["last_tag_open"]   = '<li class="page-item page-link">';
$config["last_tag_close"]  = '</li>';
$config["next_tag_open"]   = '<li class="page-item"><span aria-hidden="true">';
$config["next_tag_close"]  = '</span></li>';
$config["prev_tag_open"]   = '<li class="page-item"> <span aria-hidden="true">';
$config["prev_tag_close"]  = '</span></li>';

Active Link and Number Link

Sometimes, you want to style the active link differently. You could do that by applying wrapper tags as shown below.

$config["cur_tag_open"]    = '<li class="page-item active"> <a>';
$config["cur_tag_close"]   = '</a></li>';

-- Table structure for table `az_users`

CREATE TABLE `az_users` (
  `user_id` int(11) NOT NULL,
  `user_name` varchar(50) DEFAULT NULL,
  `user_email` varchar(50) DEFAULT NULL,
  `reg_date` date DEFAULT NULL,
  `user_password` varchar(100) DEFAULT NULL,
  `user_status` enum('Y','N') NOT NULL DEFAULT 'N',
  `user_mobile` bigint(20) DEFAULT NULL,
  `user_update` date DEFAULT NULL,
  `user_profile` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `az_users`
--
INSERT INTO `az_users` (`user_id`, `user_name`, `user_email`, `reg_date`, `user_password`, `user_status`, `user_mobile`, `user_update`, `user_profile`) VALUES
(4, 'Amit Kumar', '[email protected]', '2020-01-12', 'xxxxxxx', 'Y', xxxxxxx, NULL, NULL),
(5, 'Monu Kumar Sinha', '[email protected]', '2020-01-12', 'xxxxxxx', 'Y', xxxxxxx, NULL, NULL),
(6, 'Pramod Dass Dass', '[email protected]', '2020-01-12', 'xxxxxxx', 'Y', xxxxxxx, NULL, NULL),
(7, 'Janu Malik', '[email protected]', '2020-01-12', 'xxxxxxx', 'Y', xxxxxxx, NULL, NULL),
(8, 'Gopal Kumar', '[email protected]', '2020-01-12', 'xxxxxxx', 'Y', xxxxxxx, NULL, NULL),
(11, 'tse', '[email protected]', '2020-07-05', 'xxxxxxx', 'Y', xxxxxxx, NULL, NULL),
(12, 'Adil', '[email protected]', '2020-07-16', 'xxxxxxx', 'Y', xxxxxxx, NULL, NULL);
About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (51)