page-based pagination
就是常見的分頁功能拉~
page=1
offset 4 limit 5
Cursor-based pagination
id: 10,9,8,7,6
?before=6
5 4 3 2 1
id:1,2,3,4,5
?after=5
6 7 8 9 10
?after=10
11 12 13 14 15
- 簡單來說就是使用 before 跟 after ,把最後拿到的一筆資料 id 當作指標,看是要拿之前還是之後的資料。
- 我們只會拿到資料的總數,但是並不知道總共會有幾頁,這是跟做分頁功能最大的差異。
在原本拿資料的地方,我們要加上判斷 (empty($_GET['before'])的相關判斷就好了~
  $sql = 
    "SELECT id, nickname, content, created_at FROM roroiii_discussions WHERE site_key = ? " .
    (empty($_GET['before']) ? "" : "and id < ?") . 
    " ORDER BY id DESC limit 5 ";
  if (empty($_GET['before'])) {
    $stmt->bind_param('s', $site_key);  // 如果 before 的值為空,就不拿值
  } else {
    $stmt->bind_param('si', $site_key, $_GET['before']); // 如果 before 有值,就加上值
  }

![[Note] 網頁的構成要素](https://static.coderbridge.com/images/covers/default-post-cover-2.jpg)
