How to Paginate Data With PHP

I can remember years ago, when I first began coding in PHP and MySQL, how excited I was the first time I got information from a database to show up in a web browser.

For someone who had little database and programming knowledge, seeing those table rows show up onscreen based on the code I wrote (okay, so I copied an example from a book) gave me a triumphant feeling. I may not have fully understood all the magic at work back then, but that first success spurred me on to bigger and better projects.

While my level of exuberance over databases may not be the same as it once was, ever since my first ‘hello world’ encounter with PHP and MySQL I’ve been hooked on the power of making things simple and easy to use.

As a developer, one problem I’m constantly faced with is taking a large set of information and making it easy to digest. Whether it’s a large company’s client list or a personal MP3 catalog, having to sit and stare at rows upon rows upon rows of data can be discouraging and frustrating. What can a good developer do? Paginate!

Looking for a Quick Solution?

If you’re looking for a quick solution, there’s a great collection of pagination scripts and helpers over at Envato Market.

For example, try out the ZPager PHP pagination class. It makes it easy to generate listing pagination links and customize them in just a few clicks. ZPager supports Bootstrap, MySQL, and Smarty Template Engine, and it also lets you use SEO-friendly URLs.

PHP Pagination script

1. Pagination

Pagination is essentially the process of taking a set of results and spreading them out over pages to make them easier to view.

Preview

I realized early on that if I had 5,000 rows of information to display, not only would it be a headache for someone to try and read, but most browsers would take an Internet eternity (i.e. more than about five seconds) to display it. 

To solve this, I created a simple, flexible, and easy-to-use PHP class that I could use for pagination in all my projects.

2. The Database

Gotta love MySQL. No offense to the other database systems out there, but for me, all I need is MySQL. And one great feature of MySQL is that they give you some free sample databases to play with at https://dev.mysql.com/doc/#sampledb.

For my examples, I’ll be using the world database (~90k zipped), which contains over 4,000 records to play with, but the beauty of the PHP script we’ll be creating is that it can be used with any database. Now I think we can all agree that if we decided not to paginate our results, we would end up with some very long and unwieldy results like the following:

All Records Output

So let’s gets down to breaking up our data into easy-to-digest bites like this:

Preview With Pagination

Beautiful, isn’t it? Once you drop the pagination class into your code, you can quickly and easily transform a huge set of data into easy-to-navigate pages with just a few lines of code. Really.

3. The Paginator

This example will be composed of two scripts: the reusable paginator class and the index file that will display the table items and controls.

Paginator.class.php

The paginator class will have only two methods and the constructor. We will build it gradually, explaining each step as we move forward.

This definition only sets the paginator required member variables. Since this is a helper class and it’s destined for pagination only, it will rely on a valid connection to the MySQL server and an already defined query, to which we will append the parameters necessary to paginate the results. We’ll start with the constructor method.

Quite simple, right? This method only sets the object’s database connection and the necessary query. After that, it calculates the total number of rows retrieved by that query without any limit or skip parameters. This total is necessary to create the links for the paginator.

Note that, for simplicity, we are not doing error checking or any other validation of the given parameters, but in a real-world application, these checks will be necessary.

Retrieving Results

Now, let’s create the method that will actually paginate the data and return the results.

Let’s analyze this one step at a time. First, we set the limit and page parameters, which by default are set to 10 and 1 respectively. Then, we check if the user requires a given number of rows or all of them. Based on this and the page parameter, we set the LIMIT term of the query. Note that we take one from the page number because our script counts from 1 instead of from 0.

After this, we simply evaluate the query and get the results. Finally, we create a new results object which contains the limit, page, and total parameters of the executed query, as well as the data for each of the retrieved rows.

Displaying Pagination Links

Now, let’s write the method used to get the pagination links.

This is a rather long method, so let’s look over it in more detail.

First, we evaluate if the user requires a given number of links or all of them. If the user is requesting all links, then we simply return an empty string, since no pagination is required.

After this, we calculate the last page based on the total number of rows available and the items required per page.

Then, we take the links parameter, which represents the number of links to display below and above the current page, and calculate the start and end link to create.

Next, we create the opening tag for the list and set the class of it with the list class parameter. We also add the “previous page” link—note that for this link, we check if the current page is the first, and if so, we set the disabled property of the link. We also display a link to the first page and an ellipsis symbol in case the start link is not the first one.

Next, we add the links below and above the current page, based on the previously calculated start and end parameters. In each step, we evaluate the current page against the link page displayed and set the active class accordingly.

After this, we display another ellipsis symbol and the link to the last page, in case the end link is not the last one.

Finally, we display the “next page” link and set the disabled state when the user is viewing the last page, close the list, and return the generated HTML string.

That’s all there is to the Paginator class! Of course, we could add setters and getters for the database connection, limit, page, query, and total parameters, but for simplicity we’ll keep it this way.

4. The Index Page

Now we’ll create the index.php file, which is in charge of using the Paginator class and displaying the data. First, let me show you the base HTML.

Quite simple—this file only displays a table that we will populate with the information retrieved from the database. Note that for this example I’m using Bootstrap for basic page styling.

Using the Paginator

Now, to make use of our Paginator class, add the following PHP code at the top of the document.

This script is quite simple—we just required our Paginator class. Note that this code assumes that this file is in the same directory as the index.php file—if this is not the case, you should update the path accordingly.

Then, we create the connection to our database using the MySQLi library, retrieve the paginator parameters from the GET request, and set the query. Since this is not an article on MySQL, I will not get into details about the connection or the query used here.

Lastly, we create the Paginator object and retrieve the results for the current page.

Displaying the Results

Now, to display the obtained results, add the following code to the table body.

Here, we are simply iterating through the results data attribute containing the city records and creating a table row for each one of them.

Pagination Links

Now, to display the paginator links, add the following code below the table.

To the paginator createLinks method, we pass the obtained links parameter and the CSS class for the pagination links used from Bootstrap. Here is the result of the created page.

Final Output

How to Implement AJAX-Based Pagination

In this section, we’ll quickly go through how you could convert the above PHP pagination example into AJAX-based pagination. We’ll revise all the files and discuss the changes that we will need to make.

Firstly, let’s update the index.php file, as shown in the following snippet.

First of all, we’ve moved the HTML code which is required to build the pagination into the ajax_pagination.php file so that we can reuse it. Next, we’ve loaded the jQuery library and pagination.js file at the end of the file.

The ajax_pagination.php file looks like this.

It’s pretty much the same.

Next, let’s have a look at the pagination.js file.

It does a couple of things here. Firstly, it binds the click event to every pagination link. Next, when the link is clicked, it makes an AJAX call to fetch the listing data of the corresponding page and updates the page.

Finally, you need to update the createLinks method as shown in the following snippet.

Basically, we’ve added the data-page attribute to every link, so that we can get the page number when the user clicks on the link.

And with these changes in place, you’ve turned your pagination into AJAX-based pagination!

Conclusion

This should provide you with everything that you need to know in order to get up and running with pagination in your application.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

 

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

This post has been updated with contributions from Sajal Soni. Sajal belongs to India and he loves to spend time creating websites based on open source frameworks.

Leave a comment

Your email address will not be published.