Using Paging via PHP

By | June 30, 2020
Using Paging via PHP

Whenever we fetch data from the database, we are nor sure about the amount of record that is present there. We need to manage the record so that it would not look messy and should be handled in an appropriate way. So we have to divide the records to be displayed per page that’s where we use the paging technique to handle the records.

Here we use the LIMIT clause of MySQL to generate the paging. This clause takes up two arguments, first is the offset and the second argument specifies the number of records to be returned.

Vamware

Example:

<html>
   <head>
      <title>Paging Using PHP</title>
   </head>   
   <body>
<?php
   $db_host = 'localhost:3036';
   $db_user = 'root';
   $db_pass = 'rootpassword';
   $db_conn = mysql_connect($db_host, $db_user, $db_pass);
$record_limit=15;
   if(! $db_conn ) {
      die('Connection failed: ' . mysql_error());
   }
      mysql_select_db('demo_db');
$db_sql = 'SELECT count(stu_id) FROM student';
   $db_retval = mysql_query( $db_sql, $db_conn );
if(! $db_retval ) {
      die('data cannot not be retrieved: ' . mysql_error());
   }
$db_row = mysql_fetch_array($db_retval, MYSQL_NUM );
         $record_count = $row[0];
         if( isset($_GET{'page'} ) ) {
            $page = $_GET{'page'} + 1;
            $offset = $record_limit * $page ;
         }else {
            $page = 0;
            $offset = 0;
         }
         $left_rec = $record_count - ($page * $record_limit);
         $db_sql = "SELECT stu_id, stu_name, stu_salary ". 
            "FROM student ".
            "LIMIT $offset, $record_limit";
         $db_retval = mysql_query( $db_sql, $db_conn );
         if(! $db_retval ) {
            die('data cannot be retrieved: ' . mysql_error());
         }
while($db_row = mysql_fetch_array($db_retval, MYSQL_NUM)) {
      echo "STU ID :{$db_row[0]}  <br> ".
         "STU NAME : {$db_row[1]} <br> ".
         "STU ADDRESS : {$db_row[2]} <br> ".
         "--------------------------------<br>";
}
if( $page > 0 ) {
            $last = $page - 2;
            echo "<a href = \"$_PHP_SELF?page = $last\">Last 10 Records</a> |";
            echo "<a href = \"$_PHP_SELF?page = $page\">Next 10 Records</a>";
         }else if( $page == 0 ) {
            echo "<a href = \"$_PHP_SELF?page = $page\">Next 10 Records</a>";
         }else if( $left_rec < $record_limit ) {
            $last = $page - 2;
            echo "<a href = \"$_PHP_SELF?page = $last\">Last 10 Records</a>";
         }
         mysql_close($db_conn);
      ?>
   </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *