Here is an example of¬† how to use pagination in your PHP oage. I’m using a pagination class developed by Shiege¬†Iseng’ and can be downloaded from here.

We include this file in the page we use. So here is a basic script that shows the details of users from a database and shows 4 of them in a pagae and shows 3 pages as links in between the [prev] and [next] links.


<?php

//making the database connection
include_once('includes/connection/connection.inc');
 dbConnect();

//including the paging class
 require_once('paging_class.php');

//database query
 $qry = "SELECT * FROM USERS";
 $results = mysql_query($qry);
 $num_rows = mysql_num_rows($results);

//making a paging object that shows 4 results and 3 links
$paging = new paging(4,3);
 $paging->db($host,$username,$passwd,$dbName);
 $paging->query($qry);
?>

<html>
 <head>
 <title>Pagination Example</title>
 </head>

<body>

<table>
 <tr>
 <td>Total Results Found: <?php echo $num_rows; //prints total results ?></td>
 </tr>
 <tr>
 <td>Sl No</td>
 <td>First Name</td>
 <td>Last Name</td>
 <td>Sex</td>
 <td>DOB</td>
 <td>Email</td>
 </tr>

 <?php
 $sl = 1;
 $pageno = 1;
 $pageno = $pageno - 1;
 if($pageno > 0)
 $s1 = $pageno * 10;
 else
 $s1 = 0;
 ?>

 <?php
 if($num_rows > 0)
 {
 $i = 1;
 while($obj=$paging->result_assoc())
 {
 $s1 = $s1 + 1;
//to alternate b/w colors in the row
 if(($i + 1) % 2 == 0)
 $bgcolor="#dbe3f0";
 else
 $bgcolor="#dbdcf0";
 ?>

 <tr bgcolor="<?php echo $bgcolor?>">
 <td><?php echo $sl; ?></td>
 <td><?php echo $obj['firstname']; ?></td>
 <td><?php echo $obj['lastname']; ?></td>
 <td><?php echo $obj['sex']; ?></td>
 <td><?php echo $obj['dob']; ?></td>
 <td><?php echo $obj['email']; ?></td>
 </tr>

 <?php
 $i++;
 }
 }
 else
 {
 ?>

 <tr>
 <td>No Data Available !! Please redifine your Search.... </td>
 </tr>

 <?php
 }
 ?>
 <tr>
 <td><?php echo "<hr>".$paging->print_link();?></td>
 </tr>

 </table>