Monday, 4 June 2012

PHP Pagination code


<?php

//connecting to the database
$error = "Could not connect to the database";
mysql_connect('localhost','root','') or die($error);
mysql_select_db('pagination') or die($error);

//max displayed per page
$per_page = 6;

//get start variable
$start = $_GET['start'];

//count records
$record_count = mysql_num_rows(mysql_query("SELECT * FROM names"));

//count max pages
$max_pages = $record_count / $per_page; //may come out as decimal

if (!$start)
   $start = 0;
 
//display data
$get = mysql_query("SELECT * FROM names LIMIT $start, $per_page");
while ($row = mysql_fetch_assoc($get))
{
 // get data
 $name = $row['name'];
 $name_id = $row['name_id'];

 echo $name." (".$name_id.")<br />";

}

//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;

//show prev button
if (!($start<=0))
       echo "<a href='index.php?start=$prev'>Prev</a> ";

//show page numbers

//set variable for first page
$i=1;

for ($x=0;$x<$record_count;$x=$x+$per_page)
{
 if ($start!=$x)
    echo " <a href='index.php?start=$x'>$i</a> ";
 else
    echo " <a href='index.php?start=$x'><b>$i</b></a> ";
 $i++;
}

//show next button
if (!($start>=$record_count-$per_page))
       echo " <a href='index.php?start=$next'>Next</a>";

?>

No comments:

Post a Comment

Search Engine Submission - AddMe