Pagination with PHP Tutorial
Pagination is a process where the user navigates through a long webpage or an entire website by specifying the number of pages they want to see. This tutorial will teach you how to paginate data with PHP, which is a free and open-source server-side scripting language.
What is Pagination
There might be a few of you who are clueless as to even what pagination is. For those with questions, pagination is where you have more data than desired appearing on one page, and breaking up that data so that it is then presented on multiple pages. It is very likely that you have seen this before. To see a working example, click this link: Code List Notice at the very bottom, the page numbers listed, and either ‘Previous’ or ‘Next’ to the left and right. To view more pagination, simply view any tutorial on this site (allsyntax.com) and navigate to the bottom of each page.
What are the Benefits?
Pagination is excellent in that it is user-friendly. Users can navigate through what was normally a large amount of data, and it is now broken into pages which is easy to browse through. Paginating information on your site is also a benefit to you. No longer do you have large amounts of data cluttering up sections of your site. Also, if you were paginating by hand, well- then this method will save you a great amount of time, and you will not know what to do with hands that are not cramped up. This method is customizable in that you can even allow the user to determine the results per page as well.
What do I need to get Started?
There are a few things you will need before you can get started. The first is PHP. Check with your hosting if PHP is a feature. Next, access the MySQL database. The database part is not necessarily a requirement, however, this is what this tutorial is based around, and pagination is an accent to your data in the database.
Getting Started
Since we will be interacting with the database, one of your first lines of code can be to connect to the database with your username and password. I recommend having this in a single file, and just include the file when you need to connect in your scripts.
See below:
require_once($_SERVER[‘DOCUMENT_ROOT’].’/db_connect.php’);
Now we will run a query to find out how many items (rows) match the category being viewed. This will be the total amount of items that can be shown.
This query can look something like this:
$q = mysql_query(‘SELECT * FROM `code` WHERE `type` = ”.addslashes($_GET[‘cat’]).”’);
if(!$q) die(mysql_error());
$total_items = mysql_num_rows($q);
$q is the query, and after that, we make sure the query was successful. If not, we display the error. After that, $total_items will contain the value of the max amount of results. Next, we can declare a few of our important variables, $limit, $cat, and $page. The values of these variables are obtained through the $_GET method.
$limittt= $_GET[‘limit’];
$cattt= $_GET[‘cat’];
$pagett= $_GET[‘page’];
If for any reason, this data is not available, we can set defaults. This might be because someone hand-typed the URL containing these values, or because someone is intentionally attempting to cause errors in your scripts. So, we use the code:
if((!$limit) || (is_numeric($limit) == false) || ($limit 50)) {
$limit = 10; //default
}
if((!$page) || (is_numeric($page) == false) || ($page $total_items)) {
$page = 1; //default
}
The first condition will set the $limit to 10 (default) if the $limit was empty, non-numeric, less than 10, or greater than 50. The function, is_numeric(); is boolean, so it returns true if $limit is numerical, and false if it is non-numerical (containing non-numeric data). The second condition is basically the same. If $page is empty, non-numeric, less than zero, or greater than the max amount of results; Then set $page to the value of 1 (default).
Next, we will set two more variables. These will be the total number of pages needed, and the limit we set to use in our query.
$total_pages t= ceil($total_items / $limit);
$set_limit t= $page * $limit – ($limit);
$total_pages: in this variable, we get the total number of pages needed. We use the ceil(); function – This will round up any remainder we have from the calculation within. We need it to round up so that no items are left out. So, if $total_items were 27, and $limit was 10…that would return 2.7 – If we didn’t use ceil(); you can’t have .7 of a page, and if we showed 2 pages, we would lose those .7 results. So, we round that up to 3 with ceil(); and in this case = 2 pages of 10 and 1 page of 7.
$set_limit: This will contain the value of where we will start, or where we left off, depending on the value of $page and $limit. If $page was 3 and the limit was $10 then the variable will contain the value: 20. And that would be the value we use in our query for LIMIT.
The Query
The most important thing about pagination is the query. The part of our query that makes pagination possible is LIMIT. There are two ways to use LIMIT.
Example #1: SELECT `stuff` FROM `table` LIMIT 5
In the example above, the query will return the first 5 rows.
Example #2: SELECT `stuff` FROM `table` LIMIT 5, 10
In this example, the query will return 10 rows, beginning with row 5.
We will be using LIMIT with the #2 example; except where you see 5 and 10 above, we will place the variables, $set_limit and $limit.
Check out our query below:
$q = mysql_query(‘SELECT * FROM `table` WHERE `cat` = ”.addslashes($_GET[‘cat’]).” LIMIT $set_limit, $limit’);
if(!$q) die(mysql_error());
$err = mysql_num_rows($q);
if($err == 0) die(‘No matches met your criteria.’);
This is the heart of our pagination, each time the query will return different results, depending on the value of $set_limit (which changes depending on the value of $page) and what our limit is set to in $limit. Now, we’ll break down the code:
$q: We’re selecting all data from the table where the category of the table matches the category we’re in, starting with the row equaling the value of $set_limit, limiting the results to follow only to the value of $limit. After that, we check that the query was successful, and display an error if it was not.
$err: Contains the number of rows returned from the query, if that number is zero, we indicate that no matches were found.
Results per Page
We can allow the user to determine how many results per page he or she would like to see. To do this, we will provide a few links that will directly alter the value of $limit, this works because the limit is in our query string ($limit = $_GET[‘limit’]).
Here, we display the links to view different results per page:
Results per page:
10 |
25 |
See where we just alter the value of the limit in the query string? This is also why we set the conditions above where the $limit cannot be less than 10, or greater than 50.
The Results
Now we have all of our variables declared, and the query ran, so we are now a position to display our results. We will use a while loop to display the results, see the code below:
//show data matching query:
while($results = mysql_fetch_object($q)) {
echo(‘item: ‘.results->title.’
‘);
}
The code above will display each row matching the query we previously set. In the echo statement, you see result->title -This would display the title of the item in your table if you had a column named title. This is only an example, im sure the code you have to display each individual item is much larger and prettier, I just made it simple for you to see whats going on within the loop.
Displaying Prev., Next, and pages in between
So, we’ve got our results matching the query displayed, now what about the rest? Believe it or not, the hard part is done and it should be smooth sailing from here. First, we will determine if we have to display the ‘Previous’ link or not.
Here’s the code:
$prev_page = $page – 1;
if($prev_page >= 1) {
echo(‘<< Prev.‘);
}
$prev_page: This contains the value of what will be our previous page, by taking the value of our current page, and subtracting 1. Next, we check if $prev_page is greater or equal to 1. If it is, we need to display the link -so we echo it. Take a look at the link we used:
http://www.yoursite.com/stuff/script.php?cat=$cat&limit=$limit&page=$prev_page
Notice in the URL that we simply include the variables containing our current data. I would also like to take the time to say that this is a perfect case to use Mod_Rewrite for friendly URLs. Instead of having this long tedious query string, you can make the URL appear as simple as this:
http://www.yoursite.com/stuff/php/10/1.php
Where PHP is your $cat, 10 is $limit, and 1 is $page. Much, much better. And to possibly save you time, if you were to use this same exact format of URL, your Mod_Rewrite code would be:
RewriteRule ^(.*)/(.*)/(.*).php$ your_script.php?cat=$1&limit;=$2&page;=$3 [NC]
Pages in between
Getting back on track, we will now display the pages in between (not previous or next). To do so, we will use a for a loop. View the code below:
for($a = 1; $a <= $total_pages; $a++)
{
if($a == $page) {
echo(‘ $a | ‘); //no link
t } else {
echo(‘ $a | ‘);
}
}
This is a basic for loop structure, where it will loop until it is less than or equal to the value of $total_pages. Inside the for loop, we set a condition that if $a equals the current page, to just echo that value, not linked (because we’re already on that page). If not, echo the rest of the pages, linked.
Next Page
Displaying the next page link is identical to display the previous page link. Your code should look a bit like this:
$next_page = $page + 1;
if($next_page <= $total_pages) {
echo(‘Next > >’);
}
Set the value of the next page in the $next_page variable by taking the value of the current page ($page) and adding 1. Now, we have the condition that will be executed and display the backlink only if $next_page is less than or equal to the value of $total_pages. That is all for displaying the paginated links.
FYI:
I would like to bring important information to your attention. If your category names contain spaces, like, ‘visual basic’ when you try to use that in your link, it will not link properly. Because, it will only read until the space is encountered, and then stops. Your link would read, ‘visual’ instead. Therefore, we will use the function, urlencode(); to replace those spaces so that the browser can interpret them. See the code below
$cat = urlencode($cat);
Simple as that. Now, if $cat was, ‘visual basic’ it is now ‘visual+basic’ and the links will be valid, and browser friendly. Just be sure to place this line of code before the code where you begin to display the links.
Complete Code
Also, keep in mind that if you just copy and paste this script, it will _not_ work. You need to edit the script to meet your needs, like the table name, link paths, database connection, -pretty much everything. But I put in comments where changes need to be made.
Conclusion
I hope this tutorial meets your needs. If you have any questions on this script, feel free to ask in the forums. I am sure there are millions of ways to accomplish various actions in the code, but this is the way I chose to do it, which does work.