简体   繁体   English

使用PHP分析MySQL结果

[英]Paging MySQL results with PHP

How would you split MySQL results into 'next' and 'previous' if the output was very long? 如果输出很长,你会如何将MySQL结果拆分为'next'和'previous'?

$data = mysql_query("SELECT * FROM table WHERE ... AND ...")  
  or die(mysql_error());

while($info = mysql_fetch_array( $data ))
{
  echo $info['value'];
}

Where values would be listed from 1 to 10 and then go to next? 哪个值会从1到10列出然后转到下一个? The first page could be done with LIMIT 10 but how would I do the following ones? 第一页可以使用LIMIT 10完成,但我该如何进行以下操作呢?

SELECT * FROM table WHERE ... AND ... LIMIT 10 OFFSET 10

I prefer having the OFFSET word just because it's a bit more readable. 我更喜欢使用OFFSET字,因为它更具可读性。

Also remember that the offset is 0 based (the offset of the first row returned is 0, not 1). 还要记住偏移量是基于0的(返回的第一行的偏移量是0,而不是1)。 So LIMIT 10 OFFSET 10 will return rows 10 to 19. 所以LIMIT 10 OFFSET 10将返回第10行到第19行。

You can specify an offset in the LIMIT clause: 您可以在LIMIT子句中指定偏移量:

LIMIT 0, 10
LIMIT 10, 10
LIMIT 20, 10
...

So when building the LIMIT clause your code should look like that: 因此,在构建LIMIT子句时,您的代码应如下所示:

$offset = ($current_page - 1) * $items_per_page;
$sql = "[...] LIMIT $offset, $items_per_page";

Of course you'll have to ensure that $current_page is >= 1 . 当然,您必须确保$current_page >= 1 But that's easily done: 但这很容易做到:

$current_page = empty($_GET['current_page']) ? 1 : max(1, (int)$_GET['current_page']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM