Sunday, 22 January 2012

Simple pagination using PHP

We will be making use of Mysql's LIMIT functionality to do the pagination. If we do like this,
SELECT * FROM pagination limit 0,4;
the first 4 elements will be selected. The first option is the starting number and the 2nd option is the number of elements.
But first, we find out the number of rows, using
SELECT COUNT(*) FROM pagination;
Then the number of pages will be equal to count/no. of elements in one page.
We then need to pass the page number as a GET variable like this,
<a href="?page='.$i.'">' .$i.'</a>, //$i will be in a for loop incrementing from 1 to no. of pages

It is always a good idea to do the database connections on a seperate page
prepare($sql);
$stmt->bind_param('ii',$start,$num_results);
$pages = 'SELECT count(*) FROM pagination';
$stmt2 = $conn->query($pages);
$count = $stmt2->fetch_array();
$count = $count[0];
?>


The bind_param function will bind the variables $start and $num_results to dynamically insert the values for the LIMIT function.
$count stores the number of rows.

Now in the second page, we calculate the number of pages and the starting value for the LIMIT function i.e, $start which will be ($page - 1) * $num_results where $page is the page number. For example, if we click on page 3, it should display results from 2*4 =8 to 12.
But first we should check if GET is set using isset function like this,
if(isset($_GET['page'])){
  $page = $_GET['page'];
}
else $page=1;
This is to put the default page as 1.
We then execute the query using execute() and bind the results to variables.

So, here is the index.php page,
execute() or die("Error with query");
$stmt->bind_result($id,$name);

while($stmt->fetch()){
     echo $id.$name.'
'; } for($i=1;$i<$num_pages+1;$i++) { echo ($i == $page) ? '' .$i.'' : '' .$i.''; } ?>
In the final step, we have checked the condition, $i==$page to make the current page bold.

No comments:

Post a Comment