# 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.

## 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.

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:

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

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.

 1 

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.

 1 _conn = $conn;  6 $this->_query = $query;  7   8 $rs= $this->_conn->query($this->_query );  9  $this->_total =$rs->num_rows;  10   11 } 

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.

 1 _limit = $limit;  5 $this->_page = $page;  6   7  if ($this->_limit == 'all' ) {  8  $query =$this->_query;  9  } else {  10  $query =$this->_query . " LIMIT " . ( ( $this->_page - 1 ) *$this->_limit ) . ", $this->_limit";  11  }  12 $rs = $this->_conn->query($query );  13   14  while ( $row =$rs->fetch_assoc() ) {  15  $results[] =$row;  16  }  17   18  $result = new stdClass();  19 $result->page = $this->_page;  20 $result->limit = $this->_limit;  21 $result->total = $this->_total;  22 $result->data = $results;  23   24  return$result;  25 } 

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.

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

 1 _limit == 'all' ) {  4  return '';  5  }  6   7  $last = ceil($this->_total / $this->_limit );  8   9 $start = ( ( $this->_page -$links ) > 0 ) ? $this->_page -$links : 1;  10  $end = ( ($this->_page + $links ) <$last ) ? $this->_page +$links : $last;  11   12 $html = '
';  13   14  $class = ($this->_page == 1 ) ? "disabled" : "";  15  $html .= ' • « • ';  16   17  if ($start > 1 ) {  18  $html .= ' • 1 • ';  19 $html .= '
• ...
• ';  20  }  21   22  for ( $i =$start ; $i <=$end; $i++ ) {  23 $class = ( $this->_page ==$i ) ? "active" : "";  24  $html .= ' • ' .$i . '
• ';  25  }  26   27  if ( $end <$last ) {  28  $html .= ' • ... • ';  29 $html .= '
• ' . $last . ' • ';  30  }  31   32 $class = ( $this->_page ==$last ) ? "disabled" : "";  33  $html .= ' • » • ';  34   35 $html .= '
';  36   37  return $html;  38 }  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.  1   2   3  PHP Pagination  4   5   6   7   8   9  PHP Pagination  10   11  CityCountryContinentRegion  12   13   14   15   16   17   18   19   20   21   22   23   24   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  1 data );$i++ ) : ?>  2 
data[$i]['Name']; ?>data[$i]['Country']; ?>data[$i]['Continent']; ?>data[$i]['Region']; ?>
 3   4   5   6   7   8   9

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

 1 getData( $limit,$page );  14 ?> 

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.

 1 data ); $i++ ) : ?>  2  data[$i]['Name']; ?>data[$i]['Country']; ?>data[$i]['Continent']; ?>data[$i]['Region']; ?>  3   4   5   6   7   8   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.  1 createLinks($links, 'pagination pagination-sm' ); ?> 

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.

## 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.

 1   2   3  PHP Pagination  4   5   6 7   8 
 9 
 10 

PHP Pagination

 11 
 12   15 
 16 
 17 
 18   19   20   21  

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.

 1 getData( $limit,$page );  13 ?>  14 15   16 
CityCountryContinentRegion
 17   18   19   20   21   22   23   24 
data[$i]['first_name']; ?>data[$i]['last_name']; ?>data[$i]['email']; ?>data[$i]['phone']; ?>
 25  data ); $i++ ) : ?>  26   27   28   29   30   31   32   33   34   35 createLinks($links, 'pagination pagination-sm' ); ?> 

It's pretty much the same.

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

 1 $(document).on( "click", ".pagination a", function(e) {  2  var pageValue =$(this).attr("data-page");  3 4  $.ajax({  5  url: '/ajax_pagination.php?limit=25&page='+pageValue,  6  type: "GET",  7  success: function(data){  8 $("#ajax_wrapper").html(data);  9  }  10  });  11 12  e.preventDefault();  13 }); 

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.

 1 public function createLinks( $links,$list_class ) {  2  if ( $this->_limit == 'all' ) {  3  return '';  4  }  5   6 $last = ceil( $this->_total /$this->_limit );  7   8  $start = ( ($this->_page - $links ) > 0 ) ?$this->_page - $links : 1;  9 $end = ( ( $this->_page +$links ) < $last ) ?$this->_page + $links :$last;  10   11  $html = ' ';  12   13 $class = ( $this->_page == 1 ) ? "disabled" : "";  14 $html .= '
• «
• ';  15   16  if ( $start > 1 ) {  17 $html .= '
• 1
• ';  18  $html .= ' • ... • ';  19  }  20   21  for ($i = $start ;$i <= $end;$i++ ) {  22  $class = ($this->_page == $i ) ? "active" : "";  23 $html .= '
• ' . $i . ' • ';  24  }  25   26  if ($end < $last ) {  27 $html .= '
• ...
• ';  28  $html .= ' • ' .$last . '
• ';  29  }  30   31  $class = ($this->_page == $last ) ? "disabled" : "";  32 $html .= '
• »
• ';  33   34  $html .= ' ';  35   36  return$html;  37 } 

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.