PHP & Pagination
Very often I see people asking questions about this on forums such as DP and NP. I have probably posted my code snippet on how to efficiently create a simple pagination document more times than I can count (which whether you believe it or not is pretty high
). So I decided I’d go through it here.
First off, we’ll explain what pagination is. You may be reading this article not even certain if pagination is what you need. However, if you have multiple MySQL results you wish to organize and display “x” results per page, you’re on looking at the right thing. It is as simple as that. Pagination is really just web jargin used to shorten up “return results only displaying ‘x’ per page.”
So, I’m going to post the snippet and I’ll go into it a little bit, but I do believe that the comments explain pretty thoroughly. First the database structure we’re going to use
CREATE TABLE `pagination` (
`id` BIGINT( 10 ) NOT NULL ,
`name` VARCHAR( 32 ) NOT NULL ,
`content` TEXT NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;
And now.. The moment we’ve been waiting for… The actual pagination script!
<?php
/**
* Pagination Script by Dennis M.
* (C) 2009 Dennis M. All Rights Reserved.
*
* Primary purpose of this script is to teach
* people the art and concept of pagination
* and how to effectively create/use it.
* Please give credit to Dennis M. if you
* take anything directly from this script.
*
*/// Connect to DB
mysql_connect("localhost","USER","PASS");
mysql_select_db("USER_DATABASE");// Define results per page
$perPage = 1;// Define page number in URL
$num = $_GET['no'];// Define link starting point.
$linkno = 1;// If no number given, default it.
if(!isset($num) OR !is_numeric($num)){
$num = 1;
}// Multiply to see where we're at to show results
$currentLimit = $perPage*($num-1);// Get how many pages we'll have total (for links)
$numPages = mysql_num_rows(mysql_query("SELECT * FROM pagination"))/$perPage;$query = mysql_query("SELECT * FROM pagination ORDER BY id ASC LIMIT ".mysql_escape_string($currentLimit).",".mysql_escape_string($perPage).";");
// Fetch all the info
while($row = mysql_fetch_array($query)){
$title = stripslashes($row['name']);
$article = stripslashes($row['content']);
?>
<html>
<head>
<title>Pagination Test</title>
</head>
<body>
<h1><?php echo($title); ?></h1><br />
<p><?php echo($article); ?></p><br /><hr>
<?php
}
print "<p align=\"right\">";
if($perPage <= 2){
while($links < round($numPages)){
?>
<?php
$links++;
$linkno++;
}
} else {
while($links <= round($numPages)){
?>
<?php
$links++;
$linkno++;
}
}
?></p>
</body>
</html>
Now that’s all there really is to it. Basically how it works is it updates the SQL query depending on the page number (received from $_GET['no']). If none is defined, it reverts to the default and all goes accordingly!
The download link is above as usual!
Enjoy
Regards,
Dennis M.