循环遍历 MySQL 结果
我不确定这到底是如何称呼的,但我会尽力描述我想要实现的目标。
所以,首先有一个变量,叫做$id
,它实际上是$_GET['id']
。假设用户通过请求进入以下页面:/page.php?id=6
。现在我需要做的是提供数据库中接下来 3 页的信息。这是数据库:
TABLE `pages`
id | page_name
______________________
1 | AAAAA
2 | BBBBB
3 | CCCCC
4 | DDDDD
5 | EEEEE
6 | FFFFF
7 | GGGGG
8 | HHHHH
9 | IIIII
因此,在请求 id 6
的页面时,以下脚本返回接下来的 3 个页面 (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");
}
这是输出:
Page ID: 7; Page Name: GGGGG
Page ID: 8; Page Name: HHHHH
Page ID: 9; Page Name: IIIII
它工作正常,直到$id
大于 6。当它是 (/page.php?id={7/8/9}
) 时,输出不会显示 3 页更多,但2页、1页时分别没有输出$id
是 9
。
所以我的问题是:当没有足够的结果(少于3)显示时,有没有办法返回并从头开始?
- 访问
/page.php?id=8
时,输出应包含 id 为9
、1
和2
的页面>。 - 访问
/page.php?id=9
时,输出应包含 id 为1
、2
、3
的页面>。 - 访问
/page.php?id=3
时,输出应包含 id 为4
、5
、6
的页面>等等。
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 id9
,1
and2
. - When accessing
/page.php?id=9
, the output should contain pages with id1
,2
,3
. - When accessing
/page.php?id=3
, the output should contain pages with id4
,5
,6
and so on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这样你总能得到 3 页。如果下一页不够,您将从头开始最多 3 页。
This way you always get 3 pages. If not enough next pages, you will get up to 3 from the beginning.
您可以将查询修改为如下所示:
You could modify the query to be something like:
我会用这种方式解决(一个可能的问题是结果集最多可以包含 6 条记录而不是 3 条):
I would solve this way (one possible issue is that the resultset could contain at most 6 records instead of 3):