用PHP和MySQL分页

时间:2011-03-18 11:42:58

标签: php mysql pagination

我已尝试过大量不同的代码片段,以便在我的结果集中使用分页。我在每种情况下都遇到同样的问题。在查询结束时使用LIMIT我可以正确显示第一页以及正确页数的导航链接(因此执行计算的代码返回的行数和每页显示的数字是正确的),但是当您单击以跟随指向任何其他页面的链接时,它们将为空白。那么如何让更新的查询再次运行并在后续页面上显示我的结果呢?

这是我尝试过的一段代码:

$rowsperpage = 10;
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { $currentpage = (int) $_GET['currentpage']; } 
else { $currentpage = 1; } 

// if current page is greater than total pages...
if ($currentpage > $totalpages) { $currentpage = $totalpages; } 

// if current page is less than first page...
if ($currentpage < 1) { $currentpage = 1; } 

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;

// run the query
$sql = "SELECT * FROM table WHERE keyword LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $link) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
{   
     //echo data for each record here
} 

// building pagination links 
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {   
    // show << link to go back to page 1   
    echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";   
    // get previous page num   
    $prevpage = $currentpage - 1;   
    // show < link to go back to 1 page   
    echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

由于href太多,不允许显示其余的导航代码,但链接显示正确。问题似乎是查询如何转移到下一页。

1 个答案:

答案 0 :(得分:3)

您必须使用limit offset, rowcount

通常用于nth page

offset= (n-1)*pagesizerowcount=pagesize