Simple PHP Pagination script

Simple PHP Pagination script

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Simple PHP Pagination Script

Handling rows of data from a database often leads to one inevitable conclusion: displaying them all on a single page is a bad idea. If you are building a legacy application or working within a vanilla PHP environment without an ORM, implementing pagination requires a deliberate approach to SQL construction and state management. The "easiest" way isn't necessarily the most secure or scalable if you ignore how the query limits results and calculates offsets.

The core mechanism relies on two specific SQL clauses: LIMIT and OFFSET. You cannot simply loop through an infinite result set; you must explicitly tell the database how many records to return and where to start. A robust pagination script needs three distinct pieces of data from your controller or view: the total number of rows in the dataset, the current page number, and the number of items per page.

Here is a minimal, dependency-free example of how to structure this logic in raw PHP. First, determine the configuration constants. Setting these at the top of your file prevents magic numbers scattered throughout your codebase.

<?php
define('ITEMS_PER_PAGE', 20);
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($currentPage - 1) * ITEMS_PER_PAGE;

The next step involves querying the total count of records without applying limits. This is critical for generating the navigation links at the bottom of your table. If you query with LIMIT included, you won't know how many pages exist, and your "Next" link will break when there are no more results.

$countSql = "SELECT COUNT(*) as total FROM your_table_name";
$result = $pdo->query($countSql);
$totalRecords = $result->fetch()['total'];
$totalPages = ceil($totalRecords / ITEMS_PER_PAGE);

Once you have the metadata, you can construct the actual data retrieval query. This is where many developers make a mistake: failing to sanitize the $currentPage variable. Even if your application runs in a trusted environment, relying on raw user input for SQL parameters invites injection attacks. Use prepared statements or PDO placeholders strictly for dynamic values like the offset and limit count.

$sql = "SELECT * FROM your_table_name LIMIT :offset, :limit";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':offset' => $offset, 
    ':limit' => ITEMS_PER_PAGE
]);
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

Generating the navigation links requires a bit more logic. You need to render links for pages that exist within your calculated range. A common pitfall is trying to link to page 0 or negative numbers; ensure your loop starts from max(1, $currentPage - 2) and ends at min($totalPages, $currentPage + 2). This keeps the pagination controls clutter-free by only showing relevant pages around the current one.

for ($page = max(1, $currentPage - 2); $page <= min($totalPages, $currentPage + 2); $page++) {
    echo "<a href="?page=$page&other_param=value>Page $page</a>";
}

If you find yourself managing sessions, flash messages, or complex routing alongside this logic, the overhead of raw PHP might start to outweigh its simplicity. In such scenarios, frameworks like Laravel offer a cleaner abstraction. The paginate() method handles the SQL construction and offset calculation internally, reducing the chance of human error in your queries. You can find more advanced patterns for handling large datasets or custom pagination views at https://laravelcompany.com.

However, sticking to the manual approach ensures you understand exactly what is happening under the hood, which is invaluable when debugging performance issues or optimizing database indexes for specific query patterns.

Our network