Database

PHP PDO Pagination Example

PDO pagination with validated page size and integer-bound LIMIT/OFFSET.

Overview

PDO pagination with validated page size and integer-bound LIMIT/OFFSET.

What this script does

This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.

Source code

<?php
declare(strict_types=1);
function paginate(PDO $pdo,int $page,int $perPage=20): array {
    $perPage=min(100,max(1,$perPage)); $total=(int)$pdo->query('SELECT COUNT(*) FROM articles')->fetchColumn();
    $pages=max(1,(int)ceil($total/$perPage)); $page=min(max(1,$page),$pages); $offset=($page-1)*$perPage;
    $s=$pdo->prepare('SELECT id,title,slug FROM articles ORDER BY id DESC LIMIT :lim OFFSET :off');
    $s->bindValue(':lim',$perPage,PDO::PARAM_INT); $s->bindValue(':off',$offset,PDO::PARAM_INT); $s->execute();
    return ['items'=>$s->fetchAll(PDO::FETCH_ASSOC),'page'=>$page,'pages'=>$pages,'total'=>$total];
}

Download starter source: Download PHP PDO Pagination Example source

Installation and customization

  1. Review the code and required PHP extensions.
  2. Configure database and storage settings outside the public web root where applicable.
  3. Add authorization, rate limiting and logging for public-facing endpoints.
  4. Test valid, invalid and boundary inputs before deployment.

> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.