Simple PHP Paging
Its possible that your SQL SELECT statement query may result into thausand of records. But its is not good idea to display all the results on one page because your page will load very slow. So we can divide this result into many pages as per requirement.
Paging means showing your query result in multiple pages instead of just put them all in one long page. Imagine waiting for five minutes just to load a search page that shows 1000 result. By splitting the result in multiple pages you can save download time plus you don't have much scrolling to do.
MySQL helps to generate paging by using LIMIT clause which will take two arguments. First argument as OFFSET and second argument how many records should be returned from the database.
Below is a simple example to fetch records using LIMIT clause to generate paging.
Example:
Try out following example to display 10 records per page.
// Connect database.
$host="localhost"; // Host name.
$db_user="Your MySql User Name ";
$db_password="Your MySql Password";
$database="tutorial"; // Database name.
mysql_connect($host,$db_user,$db_password);
mysql_select_db($database);
$start=$_GET['start']; // starting value of query
if(!isset($start)) $start = 0; //if $start is null then assign 0
$limit=10; // limits of records
$query="select * from tutorials LIMIT $start,$limit";
$result=mysql_query($query) or die(mysql_error());
echo "<h2>PHP Paging</h2>";
// include("ads_inc/adunits_home.php");
while($myrows=mysql_fetch_array($result)){
print "<a href='#'>".$myrows['title']."</a><br />";
}
/* Get total number of records */
$query = "SELECT count(*) as count FROM tutorials";
$results = mysql_query($query);
$row = mysql_fetch_array($results);
$numrows = $row['count'];
$i=0; //
$number=1;
if($start > 0)
echo "<a href=" . $_SERVER['PHP_SELF'] . "?start=" . ($start - $limit) .
">Previous</a>";
for($i=0;$i < $numrows;$i=$i+$limit){
if($number <> $eu){
echo " <a href='".$_SERVER['PHP_SELF']."?start=$i'><font face='Arial' size='2'>$number</font></a>";
}
else { echo "<font face='Arial' size='2' color='red'>$number</font>";
} /// Current page is not displayed as link and given font color red
$number=$number+1;
}
if($numrows > ($start + $limit))
echo " <a href=\"" . $_SERVER['PHP_SELF'] . "?start=".($start + $limit).">Next</a>";
?>
