Paging Results in PHP
by Scud Monday, September 04, 2006
Rating:
Vote this news:
Following examples teaches how to query a mySQL database and getting results in pages. Every page displays results maximum 10 results in a single page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Paging Results in PHP</title>
</head><body>
<?php
mysql_connect("localhost","username","password"); //(mysql server, username, password)
mysql_select_db("mynews") or die("Can not find database"); //type here your database, mynews etc ...
if (empty($page)) {
$s=0;
}
else
{
$s = $page;
}
// SQL Query with limiting results
// 10 results will be displayed in each page
$limitQuery = 10;
$query = "select newsID, title, summary from newsTable LIMIT $s, $limitQuery" ;
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>There is no any news found .... </h4>";
}
$result = mysql_query($query) or die("SQL Query failed ...");
$count = 1 + $s ;
while ($row= mysql_fetch_array($result)) {
$title = $row["title"];
$newsID = $row["newsID"];
echo "<h1><a href=\\"read.php?id=$newsID\\">"$title</a></h1>" ;
echo "<br>$summary</br>" ;
$count++ ;
}
$currPage = (($s/$limitQuery) + 1);
echo "<br />";
if ($s>=1) {
$prevs=($s-$limit);
print " <a href=\\"$PHP_SELF?page=$prevs\\"><<
Prev 10</a>  ";
}
$pages=intval($numrows/$limit);
if ($numrows%$limit) {
$pages++;
}
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
$news=$s+$limit;
echo " <a href=\\"$PHP_SELF?page=$news\\">Next 10 >></a>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Pages $b to $a of $numrows</p>";
?>
</body>
</html>
Happy Coding !



