3 Votes Vote

Looping through MySQL Results

Posted by topdog 199 days ago Questions| mysql pages page All

I'm not sure exactly how this is called but I'll try to describe as good as I can what I want to acheive.

So, first of all, there is a variable, called $id, which is actually $_GET['id']. Assuming the user is entering the following page by requesting: /page.php?id=6. Now what I need to do is to provide the information about the next 3 pages from database. Here is the database:

  TABLE `pages`

  id   |   page_name
  ______________________
  1    |   AAAAA
  2    |   BBBBB
  3    |   CCCCC
  4    |   DDDDD
  5    |   EEEEE
  6    |   FFFFF
  7    |   GGGGG
  8    |   HHHHH
  9    |   IIIII

So, while requesting the page with id 6, the following script returns the next 3 pages (7,8,9):

 $res = mysql_query("SELECT * FROM `pages` WHERE `id`>'".intval($id)."' ORDER BY `id` DESC LIMIT 3");
 while($arr = mysql_fetch_assoc($res))
 {
       print("Page ID: ".$arr['id']."; Page Name: ".$arr['page_name']."\n");
 }

And here is the output:

 Page ID: 7; Page Name: GGGGG
 Page ID: 8; Page Name: HHHHH
 Page ID: 9; Page Name: IIIII

And it works fine until the $id is greater then 6. When it is (/page.php?id={7/8/9}), the output doesn't show 3 pages any more, but 2 pages, 1 page and respectively no output when $id is 9.

So my question is: Is there a way to go back and start from the beginning when there are not enough results (less than 3) to display?

  • When accessing /page.php?id=8, the output should contain pages with id 9, 1 and 2.
  • When accessing /page.php?id=9, the output should contain pages with id 1, 2, 3.
  • When accessing /page.php?id=3, the output should contain pages with id 4, 5, 6 and so on.

Originally asked by: develroot on Stack Overflow

Discuss Bury


Who Voted for this Question