0

I am using PHP while() to fetch the results of a database query.

while($results = mysql_fetch_array( $galleryresult )) { // show the results };

However, I would like to paginate the results if they exceed a certain number of entries. So for example if there are more than 12 entries returned, only the first 12 will be shown.

1) How can I adapt while() so only the first 12 entries are returned on the first page.

2) Then how can I adapt while() so the 13th-24th result are returned on the second page and so on.

Nick
  • 335
  • 2
  • 3
  • 7
  • Please don't use the mysql_* API anymore. It is being deprecated by the community. It's highly insecure and inefficient. Use PDO or mysqli with prepared statements instead. – markus Nov 14 '12 at 20:24
  • Possible duplicate of [MySQL skip first 10 results](http://stackoverflow.com/questions/2827029/mysql-skip-first-10-results) – slashingweapon Nov 14 '12 at 20:26

1 Answers1

2

Modify the query such that only 12 entries are in the result set. That way you do not need to modify the while loop.

Add a parameter to the URL, that tells the script the offset that should be used in the SQL query.

Create a query that counts the total number of results. Use this to determine how many pages should be displayed in the pager.

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • This works. I retrieve the page from the URL (using $_GET). Seperately I save the number of entries per page (e.g. 12) in a variable. Then I just multiply the number of entries in a page by the current page to determine which index I am on. So for example; $imagestoshow = "12"; if(isset($_GET['p'])){ $pageindex = $_GET['p'] * $imagestoshow; } Then just add this to the SQL query: limit " .$pageindex. "," .$imagestoshow; – Nick Nov 14 '12 at 20:52