Home >>MySQL Tutorial >PHP MySQL Pagination
<?php function paginage($db,$limit) { $sql ='select FOUND_ROWS();'; $result=mysql_query($sql); $row=mysql_fetch_array($result); $numrows=$row[0]; $paglinks='<p>'; if($numrows > $limit) { $page=$_GET['page']?$_GET['page']:1; //set page click_page $currentpage=$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']; $currentpage=str_replace('&page='.$page,'',$currentpage); //now if page_click on 1 if($page==1) { $paglinks.='<PREV'; } else { $page_pre=$page-1; $paglinks.='<a href="'.$currentpage.'&page='.$page_pre.' "><PREV</a>'; } //number of pages and range(no of links show) $numofpages=ceil($numrows/$limit); $range=4; //left range and right range $l_range=max(1,$page-(($range-1)/2)); $r_range=min($numofpages,$page+(($range-1)/2)); if(($r_range-$l_range)< $range-1) { if($l_range==1) { $r_range=min($l_range + ($range-1),$numofpages); } else { $l_range=max($r_range-($range-1),0); } } $paglinks.=($l_range>1)?'....':' '; for($i=1; $i<$numofpages; $i++)//for loop this make the numric page link show { if($i==$page) { $paglinks.=$i; } else { if($l_range<= $i and $i<=$r_range) { $paglinks.='<a href="'.$currentpage.'&page='.$i.'">['.$i.']</a>'; } } } $paglinks.=($r_range< $numofpages)?'....':' '; if($numrows-($limit * $page)>0) { $pagenext=$page +1; $paglinks .= '<a href="'.$currentpage.'&page='.$pagenext.'"> NEXT></a>'; } else { $paglinks .='NEXT>'; } } else { $paglinks.='<PRVE NEXT> '; } $paglinks.='</p>'; return $paglinks; } ?>
<?php include("paginate.php"); $conn=mysql_connect("localhost","root"); $db=mysql_select_db("test",$conn); error_reporting(1); ?> <body> <table border="1" class="list" cellpadding="4px" > <tr> <td>SN</td> <td>Name</td> <td>Email</td> <td>Mobile</td> </tr> <?php $page=$_GET['page']?$_GET['page']:1; $limit=5; $start=($page-1)*$limit; $query4='select SQL_CALC_FOUND_ROWS * from userinfo limit '.$start.','.$limit; $result=mysql_query($query4); $page_links=paginage($db,$limit); $num=1; while($row=mysql_fetch_array($result)) { echo'<tr>'; echo'<td>'.$row['id'].'</td>'; echo'<td>'.$row['name'].'</td>'; echo'<td>'.$row['email'].'</td>'; echo'<td>'.$row['mobile'].'</td>'; $num++; echo'</tr>'; } ?> <tr> <td colspan="6" align="center"><?php echo $page_links; ?></td> </tr> </table> </body> </html>