Thursday, January 27, 2011

PHP/MySQL paging - showing your query result in multiple pages


To show the result of a query in several pages first you need to know how many rows you have and how many rows per page you want to show. By splitting the result in multiple pages you can save download time plus you don't have much scrolling to do.
Code: 


<?php
 ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'mypasswd';

$database = 'jiansen_db';
$table = 'user_table';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// sending query
$query = mysql_query("SELECT COUNT(val) AS numrows FROM {$table}");

$result  = mysql_query($query) or die('Error, query failed');
$row     =mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$num_pages = 0;
  $page = 0;
  $results_per_page = 10;
     $num_pages = max(ceil($numrows/$results_per_page), 1);
    $page = intval($_GET['page']);
   if (!$page) {
     $page = 1;
    }  
$offset = ($page-1)*$results_per_page;
// print the link to access each page
$self = $_SERVER['PHP_SELF'];
 echo '<table border="1"><tr>';
    for ($i=1; $i<=$num_pages;$i++){
    if(!($i%10))  echo '</tr><tr>';
        echo "<td>";
          if  ($i != $page)
                    echo ' " <a href=\"$self?page=$page\">$page</a> "';
         else
                    echo "$page";
         echo "</td>";
 }
echo "</tr></table>";

$query = " SELECT val FROM {$table} " .
         " LIMIT $offset, $results_per_page";
$result = mysql_query($query) or die('Error, query failed');

// print output, depend on in which page
while($row = mysql_fetch_assoc($result))
{
   echo $row['val'] . '<br>';
}
?>


No comments:

Post a Comment