您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用MySQL LIMIT,OFFSET的分页

使用MySQL LIMIT,OFFSET的分页

首先,不要为每个页面使用单独的服务器脚本,这只是疯狂。大多数应用程序通过使用URL中的分页参数来实现分页。就像是:

http://yoursite.com/itempage.PHP?page=2

您可以通过访问所需的页码$_GET['page']

这使您的sql编写非常简单:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

因此,例如,如果此处输入为page=2,每页有4行,则您的查询为“

SELECT * FROM menuitem LIMIT 4,4

因此,这是分页的基本问题。现在,您有了附加的要求,即您希望了解页面的总数(以便可以确定是否应显示“ NEXT PAGE”,还是要允许通过链接直接访问页面X)。

为此,您必须了解表中的行数。

您可以在尝试返回实际的受限记录集之前简单地通过数据库调用完成此操作(我之所以这么说是因为您显然想验证所请求的页面是否存在)。

这实际上很简单:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = MysqLi_query($con, $sql);
if(false === $result) {
   throw new Exception('Query Failed with: ' . MysqLi_error());
} else {
   $row_count = MysqLi_num_rows($result);
   // free the result set as you don't need it anymore
   MysqLi_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.PHP?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}
MySQL 2022/1/1 18:14:51 有575人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶