Key Takeaways
- Pagination in CodeIgniter can be implemented using the built-in pagination library, which allows for a more user-friendly experience, especially when dealing with large datasets from a database.
- The process involves creating a model for counting and fetching data, setting up a controller to load the model and pagination library, and configuring pagination options such as base URL, total row count, rows per page, and the URL segment for the page section.
- The view file displays the paginated data and the pagination links. More configuration options can be used to optimize the pagination links, such as disabling first/last previous/next links and calculating the number of pages.
- CodeIgniter provides flexibility to customize pagination links, integrate AJAX for dynamic content loading, handle large datasets, use pagination with a search function, multiple pages, custom URLs, Bootstrap, SEO-friendly URLs, and different languages.
The Model
We’ll start by creating a model in the application which needs to do two things: provide a count of all the records in theCountry
table, and retrieve a list of countries from the table. Save the following as models/countries.php
:
class Countries extends CI_Model
{
public function __construct() {
parent::__construct();
}
public function record_count() {
return $this->db->count_all("Country");
}
public function fetch_countries($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("Country");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
}
CodeIgniter’s database class with Active Record is used to count and retrieve the data from the database.
The record_count()
method returns the number of records and is needed because one of the options in the $config
array for the pagination library is $config["total_rows"]
. The library will use this along with other options we set to work out how to divide the results up into pages.
The fetch_countries()
method retrieves a list of all the records from the Country
table. There are two arguments for this method: $limit
and $start
. They will be passed into the query to determine how many records to return, and what record to start from. The arguments will be set in the controller.
The Controller
Next, we need to create a method in the defaultWelcome
controller (controllers/welcome.php
) called example1()
. But just before we do that, we’ll need to load the model and also the pagination library in the class’ constructor.
<?php
class Welcome extends CI_Controller
{
public function __construct() {
parent:: __construct();
$this->load->helper("url");
$this->load->model("Countries");
$this->load->library("pagination");
}
public function example1() {
$config = array();
$config["base_url"] = base_url() . "welcome/example1";
$config["total_rows"] = $this->Countries->record_count();
$config["per_page"] = 20;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->Countries->
fetch_countries($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view("example1", $data);
}
}
The example1()
method starts by providing some of the most common configuration options for the pagination library. The options are placed in an array which is then passed as an argument to the library’s initialize method. The library requires the options must pass a base URL, a total row count, how many rows per page we want, and which part of the URL will contain the page section the user is using.
Remember those parameters that were set required by the query for a list of countries ($limit
and $start
)? Those are set next in the call to the model’s fetch_countries()
method. The $page
variable uses the ternary operator to either set its value to whatever is in the third segment of the URI string or to zero (meaning the user is on the first page).
Finally, the create_links()
method of the pagination library creates the pagination links and then we load the view to display the outcome.
The View
For the view file, we can copy theviews/welcome_message.php
and called it example1.php
and replace most of the content of the body with the following:
<body>
<div id="container">
<h1>Countries</h1>
<div id="body">
<?php
foreach($results as $data) {
echo $data->Name . " - " . $data->Continent . "<br>";
}
?>
<p><?php echo $links; ?></p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
</body>
So now when you visit http://yourdomain/welcome/example1
you should see something like this:
More Config Options
Click the pagination links and you should find yourself moving through the 239 records in theCountry
table. But you may notice that the number of linked digits change. Initially there were there digits, and later there five!
There is a config item that might help to solve this problem. It’s probably useful at this stage to remember that we are retrieving records from a database and CodeIgniter has to re-calculate the digit links as each page is accessed. The first thing we can do is to disable the first/last previous/next links to tidy up the navigation. It doesn’t stop the expanding digits, but it does tidy things up.
The second thing we can do is calculate how many pages there are by dividing the total rows by the number of rows required per page, round the result, and pass it to the $config["num_links"]
parameter.
Here’s what the example1()
method looks like with those changes:
public function example1() {
$config["base_url"] = base_url() . "welcome/example1";
$config["total_rows"] = $this->Countries->record_count();
$config["per_page"] = 20;
$config["uri_segment"] = 3;
$choice = $config["total_rows"] / $config["per_page"];
$config["num_links"] = round($choice);
$this->pagination->initialize($config);
$page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;
$data["results"] = $this->Countries
->fetch_countries($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view("example1", $data);
}
This will improve the links now.
Summary
Now you know how to use the most useful configuration options for the CodeIgniter pagination library, and you can also fix the way the pagination links are displayed to provide a consistent experience for your users. A user guide comes with every download of CodeIgniter, so be sure to check the other configuration options for the library there. It contains options for styling the pagination links, and changing the way the links are rendered on the page. Image via Alexis Puentes / Shutterstock And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start PHP. Comments on this article are closed. Have a question about PHP frameworks? Why not ask it on our forums?Frequently Asked Questions (FAQs) about Pagination with CodeIgniter
How can I customize the pagination links in CodeIgniter?
CodeIgniter provides a flexible way to customize pagination links. You can do this by configuring the pagination library. The library has an array of preferences that you can set according to your needs. These preferences include ‘base_url’, ‘total_rows’, ‘per_page’, ‘num_links’, and many more. You can also customize the full tag open, full tag close, first link, last link, next link, prev link, cur_tag_open, cur_tag_close, num_tag_open, and num_tag_close to style your pagination links.
How can I integrate AJAX with CodeIgniter Pagination?
Integrating AJAX with CodeIgniter Pagination can enhance the user experience by loading the content dynamically without refreshing the entire page. You can do this by creating a function in your controller that fetches the data and returns it in a format that can be processed by AJAX, such as JSON. Then, in your AJAX function, you can call this controller function and update the content of your page based on the returned data.
How can I use CodeIgniter Pagination with a database?
CodeIgniter Pagination can be used with a database by fetching the data from the database in your controller and passing it to the view. You can use the ‘total_rows’ preference in the pagination library to specify the total number of records in your database. Then, in your view, you can loop through the data and display it along with the pagination links.
How can I handle large datasets with CodeIgniter Pagination?
Handling large datasets with CodeIgniter Pagination can be achieved by using the ‘per_page’ preference in the pagination library. This preference allows you to specify the number of records to be displayed per page, thus breaking down your large dataset into manageable chunks. You can also use the ‘num_links’ preference to control the number of links displayed at a time.
How can I use CodeIgniter Pagination with a search function?
CodeIgniter Pagination can be used with a search function by modifying your controller function to accept a search term as a parameter. This search term can then be used in your database query to fetch the relevant data. You can also pass this search term to your view and include it in your pagination links so that the search term is preserved across different pages.
How can I use CodeIgniter Pagination with multiple pages?
CodeIgniter Pagination can be used with multiple pages by setting the ‘base_url’ preference in the pagination library to the URL of your controller function. This function can then accept a page number as a parameter and use it to calculate the offset for your database query. This way, you can fetch and display the data for the corresponding page.
How can I use CodeIgniter Pagination with a custom URL?
CodeIgniter Pagination can be used with a custom URL by setting the ‘base_url’ preference in the pagination library to your custom URL. You can also use the ‘uri_segment’ preference to specify the segment of your URL that contains the page number. This way, CodeIgniter can correctly generate the pagination links based on your custom URL.
How can I use CodeIgniter Pagination with Bootstrap?
CodeIgniter Pagination can be used with Bootstrap by customizing the full tag open, full tag close, first link, last link, next link, prev link, cur_tag_open, cur_tag_close, num_tag_open, and num_tag_close preferences in the pagination library. You can set these preferences to the corresponding Bootstrap classes to style your pagination links according to the Bootstrap theme.
How can I use CodeIgniter Pagination with SEO-friendly URLs?
CodeIgniter Pagination can be used with SEO-friendly URLs by using the ‘enable_query_strings’ option in your CodeIgniter configuration file. This option allows you to use query strings in your URLs, which can be more SEO-friendly. You can also use the ‘page_query_string’ preference in the pagination library to specify the query string variable that contains the page number.
How can I use CodeIgniter Pagination with different languages?
CodeIgniter Pagination can be used with different languages by using the ‘language’ option in your CodeIgniter configuration file. This option allows you to specify the language for your application. You can also use the ‘first_link’, ‘last_link’, ‘next_link’, and ‘prev_link’ preferences in the pagination library to specify the text for the first, last, next, and previous links in your chosen language.
Andy Hawthorne is from Coventry in the UK. He is a senior PHP developer by day, and a freelance writer by night, although lately that is sometimes the other way around.