分页结果时如何让查询转移到后续页面

2022-01-04 00:00:00 php mysql pagination

我浏览了网站上所有的分页问题和答案,在所有冗长的代码和面向对象的解决方案中,这段代码是最短和最简单的:

I've been going through all the pagination questions and answers on the site, and among all the long-drawn out code and OO solutions, this code is among the shortest and simplest:

<?php  
// insert your mysql connection code here  
$perPage = 10; 
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1; 
$startAt = $perPage * ($page - 1);  
$query = "SELECT COUNT(*) as total FROM table"; 
$r = mysql_fetch_assoc(mysql_query($query));  
$totalPages = ceil($r['total'] / $perPage);  
$links = ""; 
for ($i = 1; $i <= $totalPages; $i++) { $links .= ($i != $page )  ? "<a href='index.php?page=$i'>Page $i</a> " : "$page "; }   
$query = "SELECT * FROM table ORDER BY title LIMIT $startAt, $perPage";  
$r = mysql_query($query);  
// display results here the way you want  
echo $links; // show links to other pages 

但我仍然看不到如何在后续页面上使用更新的 LIMIT 重新生成查询.没有任何消息清楚地说明这一点,无论我尝试哪种代码,我都会继续得到空白的第二页.如果有人能解释如何将查询结果带到下一页,我将不胜感激.

But I still can't see how to regenerate the query with the updated LIMIT on the subsequent pages. None of the messages make this clear, and I continue to get blank second pages no matter which code I try. I'd really appreciate it if someone could explain how to get the query results to the next pages.

推荐答案

我认为您必须在查询中使用 OFFSET 标记.像这样:

I think you have to use the OFFSET token in your query. Like so:

$query = "SELECT * FROM table ORDER BY title LIMIT $perPage OFFSET $perPage * $page"; 

我希望这会有所帮助.

相关文章