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

Pagination of MySQL Query Results

By Angela Bradley, About.com

2 of 4

Variables Code Explained

After we connect to the database, we need to make sure we know what page of results to display. The if (!(isset($pagenum))) code is to check if the page number ($pagenum) isn't set, and if so set it to 1. If there is a page number already set, this code is ignored.

Next we run our query. The $data line should be edited to apply to your site, and return what you need to count results. The $rows line then simply counts the number of results for your query.

Next we define $page_rows. This is the number of results you want to display on each page, before going to the next page of results. We can then calculate the total number of pages we have ($last) by dividing the total amount of results (rows) by the number of results we want per page. We use CEIL here, to round all numbers up to the next whole number, because even a slight decimal will mean we need another page.

Next we run a check to make sure the page number is actually valid. If the number is less than one, or greater than the total pages, we simply reset it to the closest page number with content.

Finally we set the range ($max ) for our results using the LIMIT function. The starting number is determined by multiplying our results per page by one less than our current page. The duration is the number of results we display per page.

Index: Pagination of MySQL Query Results

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

2 of 4

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.