
With a few hundred collectibles and Magic: the Gathering cards already on display, with other projects coming up next with tens of thousands of items... pagination was a necessity.
From the get-go those two projects had pagination in mind, with all listing queries featuring OFFSET and LIMIT placeholders set at a generous number of 0 and 15,000 respectively to ensure I'd get all results while the pagination logic was not implemented. All was missing was to actually write the logic to calculate the pagination and, of course, how and when to render it. Took me a few hours at the end of a long night, but it's here.
The solution is somewhat simple, but yet effective:
- Ensure "prev" and "next" buttons are disabled when not needed;
- Display up to 3 numbered pages between those buttons;
- Hide the pagination block if only one page would be needed.
Code snippet
public function getLimit() {
$limit = 60;
if (empty($_POST)) {
$limit = 48;
}
return $limit;
}
public function getOffset(int $limit, int $total) {
$page = 1;
$max = ceil($total / $limit);
if (!empty($_GET['page']) && empty($_POST)) {
$page = (int)$_GET['page'] ?? 1;
}
if($page < 1) {
$page = 1;
}
elseif($page > $max) {
$page = $max;
}
return ($limit * $page) - $limit;
} 




