Sunday, September 8, 2013

Simple Pagination Script in PHP

Let's do a bit of coding in PHP with mysql as the DBMS. Here, I will present the simplest of code to make a page which shows a fixed number of records on a page with the next and previous links to access the next or previous records.I think you are confused what I am saying.

Let's take an example.
Suppose there is a database named "profile"(Let's say in MYSQL). It has a table named "tbl_comment" which has two fields cid and ctext. Now there is a php file named comment.php which will show the list of comments from the tbl_comment table. As the number of comments in the table increase, we need a system to show them systematically on the screen so that the end-user has not to scroll much to read the comments. There comes the pagination script handy.

In the code below, I will not present the page numbers. Only next and previous links will be shown. Let's assume that only each only 5 comments be shown.

Here is the PHP Pagination script for achieving this thing.
<?php
$dbc = mysql_connect("localhost", "root", "root") or die(mysql_error()); 
mysql_select_db("profile") or die(mysql_error());
$start = 0;
$limit = 6;
if(isset($_GET['start']))
{
 $start = @mysql_real_escape_string(trim($_GET['start']));
}
if(is_numeric($start) === false)
{
 $start = 0;
}
$query = "select * from tbl_comment limit ".$start.", ".$limit;
$result = @mysql_query($query);
?>
<div style="width: 20%;">
<?php
if($start > ($limit - 2))
{
 echo '<a href="comment.php?start='.($start - ($limit - 1)).'">&lt;&lt;previous</a>&nbsp;&nbsp;&nbsp;&nbsp;';
}
if(@mysql_num_rows($result) > ($limit - 1))
{
 echo '<a href="comment.php?start='.($start + ($limit - 1)).'" style="float: right;">next&gt;&gt;</a>';
}
echo "</div>";         
$i = 0;
while($row = @mysql_fetch_array($result))
{
 if($i == 5)
 {
  break;
 }
 $i ++;
 echo "<div>".$row['cid'].") ".$row['ctext']."</div>";           
}
?>
Important Points:
  • This script takes the start GET parameter, selects the records from the database starting from the value of the start GET parameter to the limit of 6. Then it checks for the next and previous links show hide logic and shows 5 comments.
  • Substitute your parameters for the database connection in the first two lines.
  • You can change $limit variable to the limit you want.
  • Replace comment.php in the hrefs of <a> tags to the php file name in which you will place this code.


2 comments: