1. Home
  2. Computing & Technology
  3. PHP / MySQL

Pagination of MySQL Query Results

By Angela Bradley, About.com

3 of 4

Query and Results

//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM topsites $max") or die(mysql_error());

//This is where you display your query results
while($info = mysql_fetch_array( $data_p ))
{
Print $info['Name'];
echo "<br>";
}
echo "<p>";

// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";

// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}

//just a spacer
echo " ---- ";

//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
This code is explained further on the next page.

3 of 4

Index: Pagination of MySQL Query Results

  1. Setting the Variables
  2. Variables Code Explained
  3. Query and Results
  4. Query and Results Explained

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. PHP with MySQL
  5. Pagination - PHP Pagination - PHP MySQL Pagination

©2008 About.com, a part of The New York Times Company.

All rights reserved.