如何在分页结果时获取查询以转移到后续页面

时间:2011-03-18 15:31:36

标签: php mysql pagination

我一直在浏览网站上的所有分页问题和答案,在所有漫长的代码和OO解决方案中,这段代码是最短和最简单的:

<?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重新生成查询。这些消息都没有说清楚,无论我尝试哪种代码,我都会继续得到空白的第二页。如果有人能解释如何将查询结果发送到下一页,我真的很感激。

2 个答案:

答案 0 :(得分:1)

我认为您必须在查询中使用OFFSET令牌。像这样:

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

我希望这会有所帮助。

答案 1 :(得分:0)

不确定为什么每次都需要选择计数(*)。我建议这样做:

<?php
/* establish the connection */
$mysqli = new mysqli (
            'localhost',  // The host to connect to
            'username',       // The user to connect as
            'password',   // The password to use
            'dbname');     // The default database to query

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s<br />\n", mysqli_connect_error());
    exit();
}

$perPage = 10;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);

/* Send a query to the server */
if ($result = $mysqli->query(
     "SELECT * FROM table ORDER BY title limit $startAt, $perPage")) {
    $rowCnt = $result->num_rows;
    echo "<h3>Page: $page</h3>\n";

    /* Fetch the results of the query and show results*/
    while( $row = $result->fetch_assoc() ) {
        printf("%s - %s<br/>\n", $row['orderDate'], $row['orderDescription']);
    }

    /* Show next page, previous page links dynamically */
    echo "<p>\n";
    // generate previous page link if current page no is after 1st page
    if ($page > 1)
        printf("<a href='%s?page=%d'>Previous Page</a>&nbsp;&nbsp;&nbsp;\n", 
           $_SERVER["SCRIPT_NAME"], ($page-1));

    // generate next page link if we were able to fetch $perPage rows    
    if ($rowCnt == $perPage) 
        printf("<a href='%s?page=%d'>Next Page</a>\n", 
           $_SERVER["SCRIPT_NAME"], ($page+1));
    echo "</p>\n";

    /* Destroy the result set and free the memory used for it */
    $result->close();
}

/* close the connection */
$mysqli->close();
?>

我正在使用php的新mysqli扩展,这里是php mysqli reference documentation

相关问题