PHP

Cursor-Based Pagination

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Cursor (keyset) pagination is faster than OFFSET on large tables — and immune to dupes/skips when rows shift. Pass the last seen ID and direction; get the next page.
PHP
Raw
<?php
function fetchAfter(PDO $db, ?int $afterId, int $limit = 25): array {
    $sql = $afterId === null
        ? "SELECT id, title FROM posts ORDER BY id DESC LIMIT $limit"
        : "SELECT id, title FROM posts WHERE id < ? ORDER BY id DESC LIMIT $limit";
    $stmt = $db->prepare($sql);
    $stmt->execute($afterId === null ? [] : [$afterId]);
    $rows = $stmt->fetchAll();
    return [
        'rows'   => $rows,
        'cursor' => $rows ? end($rows)['id'] : null,   // pass back as ?afterId=... next time
    ];
}

$first  = fetchAfter($db, null);                // newest 25
$second = fetchAfter($db, $first['cursor']);    // next 25
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.