Saturday, December 5, 2009

Pagination Using PHP

PHP is a server-side scripting language used to make dynamic web pages. Ever wonder how to paginate results from a MYSQL database using PHP? Well here is a script that I have written that could help you.
// First, make the MySql database connection:
$con=mysqli_connect('localhost','username','password','db');
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
Next, determine the number of records per page you want to see and then determine how many pages. One way to do this is by using an IF conditional and the GET method.
$display=10;
if (isset($_GET['p']) && is_numeric($_GET['p'])) { //Already been determined
$pages=$_GET['p'];
} else {// Need to determine:
// Next, count the number of records:
$q= "SELECT COUNT(id) FROM db";
$r=@mysqli_query($con,$q);
$row=@mysqli_fetch_array($r,MYSQLI_NUM);
$records=$row[0];
//Calculate the number of pages...
if ($records > $display) { // More than 1 page
$pages=ceil ($records/$display);
} else {
$pages=1;
}
}
// End of p IF.
//Determine where in the database to start returning results...
if (isset($_GET['s']) && is_numeric($_GET['s'])) {
$start = $_GET['s'];
} else {
$start=0;
}
//Make the query
$q= "SELECT id FROM db ORDER BY id ASC LIMIT $start,$display";
$r= mysqli_query($con,$q);
//Count the number of returned rows:
//$num= mysqli_num_rows($r);
//if ($num> 0) { //If it ran ok, display the records
//Make the links to the other pages, if necessary.
if ($pages > 1) {
//Determine what page the script is on:
$current_page=($start/$display) + 1;
//If it's not the first page, make a previous button:
if ($current_page !=1) {
echo 'Previous ';
}
//Make all the numbered pages:
for ($i = 1; $i <=$pages; $i++) { if ($i !=$current_page) { echo '' . $i . ' '; } else { echo $i . ' '; } }

// End of For loop.
//If it's not the last page, make a Next button:
if ($current_page !=$pages) {
echo 'Next';
}
Happy coding!

No comments:

Post a Comment

Get your own Widget