RSS

[php][tutorial] Simplest Pagination in PHP

03 Nov

Here is simplest code for pagination in php. Comments are there to make code self explanatory.

<?php

$data = array('1'=>'1','2'=>'2','3'=>'3','4'=>'4',
'5'=>'5','6'=>'6','7'=>'7','8'=>'8','9'=>'9','10'=>'10',
'11'=>'11','12'=>'12','13'=>'13','14'=>'14','15'=>'15',
'16'=>'16','17'=>'17','18'=>'18','19'=>'19','20'=>'20',
'21'=>'21');

$num_data = count($data);
if(!empty($_GET["start"])){
$start = $_GET['start'];
}else{
$start  = 0;
}

$limit           = 5; // Records per page
$current      = $start + $limit;
$back          = $start - $limit;
$next          = $start + $limit;
//Previous Page
$nav = '';
if($back >=0) {
$nav .= "<a href='?start=$back'>&laquo; Previous</a>
&nbsp;&nbsp;";
}

// Show navigation links
$x    = 1;
for($i=0;$i < $num_data;$i=$i+$limit){
if($i != $current){
$nav .= "<a href='?start=$i'>$x</a> ";
}else {
$nav .= "<b>$x </b>"; // bold selected page
}
$x    = $x+1;
}
// Next Page
if($current < $num_data) {
$nav .= "<a href='?start=$next'>Next &raquo;</a>";
}

$listing = '';
for($i= ($start+1); $i<= ($start+$limit) ; $i++)
{
$listing .= $data[$i]."<br>";
}

echo "<div align=center>".$listing."Pages: ".$nav."</div>";

?>

Thats it 🙂

I think its the simplest code for pagination in php, if you think its not, then please provide yours 🙂

Note: For showing the current number of records, following code is there

if($start+$limit >$num_data)
$c = $num_data;
else
$c = ($start+$limit);

echo "Records: ".($start+1)."-".$c." of ".$num_data; 
//1-10 of 20 etc
Advertisements
 
Leave a comment

Posted by on November 3, 2011 in php

 

Tags: , , , , , , , ,

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

 
%d bloggers like this: