Simple pagination with PDO

Count the rows, work out the page and fetch only that slice.

PHP · Simple pagination with PDOIntermediate
$perPage = 10;
$page    = max(1, (int)($_GET['page'] ?? 1));
$total   = (int)$pdo->query('SELECT COUNT(*) FROM posts')->fetchColumn();
$pages   = max(1, (int)ceil($total / $perPage));
$page    = min($page, $pages);
$offset  = ($page - 1) * $perPage;

$st = $pdo->prepare("SELECT * FROM posts ORDER BY id DESC LIMIT $perPage OFFSET $offset");
$st->execute();
$rows = $st->fetchAll();
paginationmysqlpdo