PHP Pagination of Result

Every search result pages need’s pagination (i.e) numbering the result page with limitation. In this post I will explain how to limit the MySQL query and numbering the page’s with page number according to the result page.

Steps :

1 . Query the result with limit included

2. Number the Page count accordingly.

 

Program :

<div>
<?php

mysql_connect(“yourhost”,”username”,”password”);
mysql_select_db(“students_test”);
$rowsPerPage = 10;
$pageNum = $_GET[“pagenum”];
$offset = ($pageNum – 1) * $rowsPerPage;

$sql = ‘select * from comment LIMIT ‘.$offset.’,’. $rowsPerPage;
$query = mysql_query($sql) or die(mysql_error());
echo ‘<table border=1>’;
while($r = mysql_fetch_array($query))
{
echo ‘<tr><td>’;
echo $r[“commentline”];
echo ‘</td></tr>’;
}
echo ‘</table><br>’;

?>
</div>
<?php

//Getting number of rows
mysql_connect(“your_host”,”username”,”password”);
mysql_select_db(“students_test”);
$msql = “select * from comment”;
$mquery = mysql_query($msql) or die(mysql_error());
$dbrows = mysql_num_rows($mquery);
$rows = ($dbrows)/$rowsPerPage;
$rem = $rows%$rowsPerPage;
if($rem!=0)
{
$rows++;
}
echo ‘Total Records : ‘.$dbrows.’ | Pages : ‘.$rows.’ | Rem : ‘.$rem.’ | Current Page : ‘.$pageNum;

?>
<div>
<?php
$plimit = 10;
if($rows <= 10)
{
$plimit = $rows;
}
$start = 1;
$end = $rows;
if($rows >= 1 && $rows <= $plimit)
{
$start = 1;
$end = $plimit;
}
else
{
if($pageNum == $rows)
{
$start = $pageNum-$plimit;
$end = $pageNum;
}
else
{
if($pageNum >= $rows-4 || $pageNum >= $rows-3 || $pageNum >= $rows-2 || $pageNum >= $rows-1)
{
$start = $rows-$plimit;
$end = $rows;
}
else if(($pageNum) <= 5)
{
$start = 1;
$end = $plimit;
}
else
{
$start = $pageNum-5;
$end = $pageNum+4;
}
}
}
for($i=$start;$i<=$end;$i++)
{
echo ‘<a href=”index.php?pagenum=’.$i.'”>’.$i.'</a> ‘;
} ?>
</div>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s