<?php
function paginate(PDO $db, string $sqlBody, array $params, int $page = 1, int $perPage = 25): array {
$page = max(1, $page);
$perPage = max(1, min(100, $perPage));
$offset = ($page - 1) * $perPage;
$total = (int)$db->prepare("SELECT COUNT(*) FROM ($sqlBody) AS _t")
->execute($params)
? (int)$db->query("SELECT FOUND_ROWS()")->fetchColumn() : 0;
// Simpler & portable: separate COUNT query
$countStmt = $db->prepare("SELECT COUNT(*) FROM ($sqlBody) AS _t");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$stmt = $db->prepare("$sqlBody LIMIT $perPage OFFSET $offset");
$stmt->execute($params);
return [
'rows' => $stmt->fetchAll(),
'page' => $page,
'per_page' => $perPage,
'total' => $total,
'pages' => (int)ceil($total / $perPage),
];
}
$result = paginate($db, "SELECT id, name FROM users WHERE active = ?", [1], page: 2);
Create a free account and build your private vault. Share publicly whenever you want.