Paging in PHP – PHP Paging Tutorial
PHP Paging & Automatic Pagination Tutorial - Paging made easy
I have written a php paging tutorial before. Admittedly, it wasn't the greatest. I don't think I was as clear as I wanted to be. SO I'm trying again.
At the end of this tutorial, there is a file named php-automatic-pagination.php.txt
Please download it! It will help you understand the following.
Here is what we will be making..nice, simple pagers! (Dont worry about the Image #x text, thats really not part of the tutorial)

Paging in php and automatic pagination is something every coder has to deal with when coding in php. I mean, you COULD show all results on 1 page and skip the php paging, but paging is necessary to reduce bandwidth and organize content. Paging is very easy to do and I will walk you through it step by step.
PHP automatic paging comes with a few questions:
Paging 1 : Page Size - How many results would you like to display per page?
Paging 2 : How can we bring back proper results in mysql?
Paging 3 : How can we print a pager that will help show the next items.
Decide on your page size - 10, 15, 25, 50, 100. It really depends on what you would like to do. For this tutorial I will use 15.
//we want 15 results per page
$pgsize=15;
//if there is a p variable in the query string e.g: page.php?p=5 we will get this value, else we will use 1 (page 1)
$pg=(is_numeric($_GET["p"]) ? $_GET["p"] : 1);
//lets determine where we would like to get results from
//if $pg is 1, this calculation results in 0 (we want to start from the first record in the database)
//if $pg is 2, this calculation will result in 1*15..which means we will start at the 15th index of the database (row 16)
$start=($pg-1)*$pgsize;
//let us query the database for our results
//you will notice LIMIT and $start and $pgsize.
//On page 1, this query will be SELECT * FROM image_table LIMIT 0,15 - this means return 15 rows starting at row-index 0 (row 1)
//On page 2, this query will be SELECT * FROM image_table LIMIT 15, 15 - this means we will return 15 rows starting at row-index 15 (row 16)
//On page 3, this query will be SELECT * FROM image_table LIMIT 30,15 - this means we will return 15 rows starting at row-index 30 (row 31)
GET IT?!?!?!
$imgs=mysql_query("SELECT * FROM image_table LIMIT $start, $pgsize");
//we will also need the total number of records in our table
//notice there is no limit? we want to know how many records are in the entire table!
//we can use COUNT(*), COUNT(1), or COUNT(fieldname), they will all return the same result
$img_total=mysql_query("SELECT COUNT(1) FROM image_table");
//mysql_query returns a resource id, we can use this to get the row it has returned
$img_total=mysql_fetch_row($img_total);
//the count will be the first field in this row
$img_total=$img_total[0];
//lets determine how many pages we will need
//WRONG!, this will cut off results..why?
//say we have 31 images, and our page size is 15. 31/15= ~2.x...We need to round this result up!
$max_pages=$img_total / $pgsize;
//use this line instead
$max_pages=ceil($img_total/$pgsize);
Once we have all this information, we can use a handy little function I have written named printPager. This function will print out a neat little pager. It uses a helper function named add_querystring_var which was from Added Bytes here:
http://www.addedbytes.com/code/querystring-functions/
Copy/paste this function into your page or into one of your includes:
This will print out your awesome little pager!
PHP Automatic Pagination Function
print '<div class="clear"></div>';
print '<ul class="pager">';
$i=1;
if($pg!=1){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $pg-1);
print '<li class="prev"><a href="'.$url.'"><<</a></li>';
}
while($i<=$max_pages){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $i);
if($pg==$i){
print '<li class="current">';
print '<span>'.$i.'</span>';
print "</li>";
}else{
print "<li>";
print '<a href="'.$url.'">'.$i.'</a>';
print "</li>";
}
$i++;
}
if($pg!=$max_pages){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $pg+1);
print '<li class="next"><a href="'.$url.'">>></a>';
}
print '</ul>';
print '<div class="clear"></div>';
}
function add_querystring_var($url, $key, $value) { $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); $url = substr($url, 0, -1); if (strpos($url, '?') === false) { return ($url . '?' . $key . '=' . $value); } else { return ($url . '&' . $key . '=' . $value); } }
Print Pager is called like so:
PHP Pager Styles
/*pagers*/
div.clear{clear:both;}
/spacing between numbers and sizes
ul.pager li {
float:left;
margin-right:5px;
font-size:8pt;
padding: 2px 5px 2px 5px;
}
//link color
ul.pager li a{
color:red;
}
//link hover style
ul.pager li a:hover{
text-decoration:underline;
color:red;
}
//current page styling
ul.pager li.current span{
color:red;
}
//previous and next stylings
ul.pager li.prev, ul.pager li.next{
}
Download this tutorials script! It will help you understand. Right click: php-automatic-pagination-tutorial.php and click Save as. Then get rid of the .txt extension and name it php if you would like to run it. You will need to setup a database table to use for the tutorial. It can have an id field and another field.
If you enjoyed this post please leave a comment! I like reading and responding to all my readers!
Thanks
![]()
Use HostGator 2010 Coupon Code: 994offhgpackage for $9.94 off your first month!
(First month will cost $0.01)
Easy, Simple Paging Using PHP
Easy & Simple Paging using PHP. Here is the result: (DB has 8records, Rows per page is set to 5, and we're on page 2)

Paging usually takes a while but here we will do it quickly and cleanly.
Your page will be named page.php. And when we want to switch pages we will make it page.php?pg=2.
Im sure you've seen this before. Anyways lets dive in.
I use shorthand to clean stuff up, but basically shorthand is
$returnvalue=(condition ? "true" : "false");
Example:
$is_loggedin=(isset($_SESSION["loggedin"]) ? 1 : 0);
After this statement, if the session variable is set, $is_loggedin will equal 1, else it will equal 0.
At the top of your PHP page type the following:
<?php /*paging*/ Line 1: $pg=(isset($_GET["pg"]) && is_numeric($_GET["pg"]) && $_GET["pg"]>0 ? $_GET["pg"] : 1); Line 2: $rowsperpage=10; Line 3: $offset=($pg>1 ? ($pg-1)*$rowsperpage : 0 ); Line 4: $limitstr=" LIMIT $offset, $rowsperpage"; ?>
Explanation:
First of all Limit is : LIMIT $startrowid, $number of entries to return
So LIMIT 55, 5 means start at row 55 and return 5 rows (55, 56, 57, 58, 59)
Line 1: If in the query string the pg is set e.g page.php?pg=4, and it is numeric, and greater than 0 we will assign the value of $_GET["pg"] to our $pg variable. If it is not set, or it is not numeric, or zero or less, we set the $pg variable to 1.
Line 2: We set our rows per page
Line 3: If the page is greater than 1, we set the offset to ($pg-1)*rowsperpage. If the page is 1 or less, we set offset to 0.
Line 4: We create the limit string for the sql statement. This will output something like LIMIT x, y.
(rowsperpage set to 10)
In this case page.php?pg=1
$pg = 1;
$offset = 0;
$rowsperpage=10;
$limitstr="LIMIT 0, 10"; //this string will pull 10 rows starting from row 0 (the first row) (rows 0-9)
In this case page.php?pg=3
$pg=3;
$offset= (3-1) * 10; //offset calculates to 20
$limitstr="LIMIT 20, 10"; //this string will pull 10 rows starting from and including row 20 (rows 20-29)
Ok. Now that we got that out of the way.
We will use a simple query, then we will attach our new limit string (looking at case 2 above)
$sql="SELECT * FROM MEMBERS $limitstr"; //sql = "SELECT * FROM MEMBERS LIMIT 20,10";
$res=mysql_query($sql);
while($row=mysql_fetch_array($res)){
//processing if you need to
}
We also need to know the total count for this table
$sql="SELECT COUNT(memberid) FROM MEMBERS";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
$total = $row[0];
Now we know the total count.
So we need to calculate the number of pages. That is done by this formula:
($total/$rowsperpage);
Now in the case of 26 members and 5 rows per page. Using this formula 26/5 = 5.2pages, so we need to round up!
$maxpage=ceil($total/$rowsperpage); //max page is now 6.
Ok, we got everything set up
Just need to print out our paging!
Wherever you want your paging setup add this:
<?php
print '<div class="paging"><ul>';
for($i=1; $i<=$maxpage; $i++){
if($pg==$i)
print '<li><span>'.$i.'</span></li>';
else
print '<li><a href="?pg='.$i.'">'.$i.'</a></li>';
}
print "</ul></div>";
?>
Then we can do some nice styling (Mess around with margins to setup spacing)
CSS
div.paging {text-align: center; margin-top: 5px;}
div.paging span{font-weight: bold;}
div.paging ul{overflow: hidden;}
div.paging ul li{width: 10px; float: left; margin: 0px 10px 5px 0px;}
This will page across until it hits the edge of the div, then it will move to the next line.
ENJOY and comment !