Real simple PHP pagination!
After searching the interwebs for simple PHP pagination and failing to add it to the (non-Yahoo) store I’ve been building, I was fed up and just thought “why can’t I make one myself?”
This is not the typical “Yahoo E-commerce” post for which E-comm Solution is known. We’re spreading our wings and branching out into WordPress and all-around web design, not limited to the Yahoo platform.
So here is a quick and dirty post on pagination for your PHP/MySQL based site. If you see anything wrong or something needs to be changed just leave a comment and it will be addressed.
Lets start with the code.
// Query to count rows.
$result = mysql_query("SELECT * FROM Table_Name WHERE Column_Name = ‘$section‘");
$items = 32; // number of items per page.
$all = $_GET[‘a’];
$num_rows = mysql_num_rows($result);
if($all == "all"){
$items = $num_rows;
}
$nrpage_amount = $num_rows/$items;
$page_amount = ceil($num_rows/$items);
$page_amount = $page_amount-1;
$page = mysql_real_escape_string($_GET[‘p’]);
if($page < "1"){
$page = "0";
}
$p_num = $items*$page;
//end paging code
// Query that you would like to SHOW
$result = mysql_query("SELECT * FROM Table_Name WHERE Column_Name = ‘$section‘ ORDER BY ‘name’ ASC LIMIT $p_num , $items");
function paging(){
global $num_rows;
global $page;
global $page_amount;
global $section;
if($page_amount != "0"){
echo "<div class=paging>";
if($page != "0"){
$prev = $page-1;
echo "<a href=\"section.php?q=$section&p=$prev\">Prev</a>";
}
for ( $counter = 0; $counter <= $page_amount; $counter += 1) {
echo "<a href=\"section.php?q=$section&p=$counter\">";
echo $counter+1;
echo "</a>";
}
if($page < $page_amount){
$next = $page+1;
echo "<a href=\"section.php?q=$section&p=$next\">Next</a>";
}
echo "<a href=\"section.php?q=$section&a=all\">View All</a>";
echo "</div>";
}
}
// call on Pagination with function
paging();
The code is simple, and you’ll just need to add your MySQL statements. The first one counts the rows and the second one displays the rows with the Pagination in effect.
The Paging part of the script was built into a function so you can add the code above and below the table that you display and all you need to do is call on paging(); on any line.
With this script I have to assume that you have a basic understanding of PHP and MySQL queries to get a table up and running and this will just be added to your page, I also would like to say that I will be updating this script and when I do I will update this post.
If there are any errors or issues with this script just comment below and I will be more than happy to address them. Enjoy!
1 Comment
Other Links to this Post
-
Real simple PHP pagination! — June 20, 2011 @ 8:09 pm
RSS feed for comments on this post.
Leave a comment
You must be logged in to post a comment.