PHP

Paginated Query Helper

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Run a SELECT with LIMIT/OFFSET and also return the total row count, so you can render "Page 3 of 47" UIs. Single function, two round trips.
PHP
Raw
<?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);
Tags

Save your own code snippets

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