Thursday, November 27, 2014

simple pagination in php





Below is the code to do a simple pagination in php:

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 5;

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydatabase');
/* Get total number of records */
$sql = "SELECT count(prd_code) as count_prd FROM Product_tab";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval );
$rec_count = $row['count_prd'];

if( isset($_GET{'page'} ) )
{
   $page = $_GET{'page'} + 1;
   $offset = $rec_limit * $page ;
}
else
{
   $page = 0;
   $offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);

$sql = "SELECT prd_code,prd_name,prd_price from product LIMIT $offset, $rec_limit";

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval))
{
    echo "Product id :{$row['prd_code']}  <br> ".
      "Product name :{$row['prd_name']}  <br> ".
         "Price : {$row['prd_price']} <br> ".         "--------------------------------<br>";
} 

if( $page > 0 && !($left_rec < $rec_limit) )
{
   $last = $page - 2;
   echo "<a href=\"$_PHP_SELF?page=$last\">Previous 5 Records</a> |";
   echo "<a href=\"$_PHP_SELF?page=$page\">Next 5 Records</a>";
}
else if( $page == 0 )
{
   echo "<a href=\"$_PHP_SELF?page=$page\">Previous 5 Records</a>";
}
else if( $left_rec < $rec_limit )
{
   $last = $page - 2;
   echo "<a href=\"$_PHP_SELF?page=$last\">Previous 5 Records</a>";
}
mysql_close($conn);
?>


See the effect here:

First page:

Middle page:

Last page: