Friday, January 22, 2010

How To Create A Pagination In PHP

Use Pagination to display results of your MySQL query over multiple pages in PHP.

Note : Remove "\" with a href tag

pagination.php

 ////// Connection with mysql Database////////

$connect = mysql_connect("yourhostname", "username", "password", "true") or die(mysql_error());
mysql_select_db("databaseName", $connect) or die(mysql_error());

////// pagination limit 10 records in a page //////

$limit =10;
if(!isset($_GET['page']))
{
     $page=1;
}
else
{
    $page=$_GET['page'];
}
$limitstart = ($page-1)*$limit;
$strgry = "select * from tableName";
$num =mysql_num_rows(mysql_query($strgry));
$pages = ceil($num/$limit);
$strgry = "select * from tableName Limit $limitstart, $limit";
$query = mysql_query($strgry) or die (mysql_error());
while($row=mysql_fetch_array($query))
{
    echo $row[0];
    echo $row[1];
    echo "\n";
}
if($page!=1)
{
    $pr=$page-1;
    echo "<\a href='pagination.php?page=$pr'>Prev<\/a>";
    echo " ";
}
for($i;$i<=$pages;$i++)
{
    if($i!=$page)
   {
        echo "<\a href='pagination.php?page=$i'>";
        echo $i;
        echo "<\/a>";
   }
   else
  {
        echo $i;
        echo " ";
   }
}
if($page!=$pages)
{
    $nxt=$page+1;
    echo "<\a href='pagination.php?page=$nxt'>Next<\/a>";
    echo " ";
}