0
0
PhpHow-ToBeginner · 4 min read

How to Create Pagination in PHP: Simple Step-by-Step Guide

To create pagination in PHP, use LIMIT and OFFSET in your SQL query to fetch a subset of records for each page. Calculate the total pages by dividing total records by items per page, then generate navigation links to switch pages.
📐

Syntax

Pagination in PHP usually involves these parts:

  • Page number: The current page number, usually from the URL query string.
  • Items per page: How many records to show on each page.
  • SQL LIMIT and OFFSET: To fetch only the records for the current page.
  • Total pages: Calculated by dividing total records by items per page.
  • Navigation links: Links to move between pages.
php
<?php
// Get current page number from URL, default to 1
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$items_per_page = 10;

// Calculate the offset for SQL
$offset = ($page - 1) * $items_per_page;

// SQL query with LIMIT and OFFSET
$sql = "SELECT * FROM table_name LIMIT $items_per_page OFFSET $offset";

// Calculate total pages
$total_records = /* get total records count from database */;
$total_pages = ceil($total_records / $items_per_page);

// Generate page links
for ($i = 1; $i <= $total_pages; $i++) {
    echo "<a href='?page=$i'>$i</a> ";
}
?>
💻

Example

This example shows a simple pagination that fetches data from a MySQL database and displays page links.

php
<?php
// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'password');

// Current page number from URL, default 1
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$items_per_page = 5;
$offset = ($page - 1) * $items_per_page;

// Get total records
$total_stmt = $pdo->query('SELECT COUNT(*) FROM products');
$total_records = $total_stmt->fetchColumn();

// Calculate total pages
$total_pages = ceil($total_records / $items_per_page);

// Fetch records for current page
$stmt = $pdo->prepare('SELECT * FROM products LIMIT :limit OFFSET :offset');
$stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Display products
foreach ($products as $product) {
    echo htmlspecialchars($product['name']) . '<br>';
}

// Display pagination links
for ($i = 1; $i <= $total_pages; $i++) {
    if ($i == $page) {
        echo "<strong>$i</strong> ";
    } else {
        echo "<a href='?page=$i'>$i</a> ";
    }
}
?>
Output
Product1 Product2 Product3 Product4 Product5 1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes when creating pagination in PHP include:

  • Not validating the page number from the URL, which can cause errors or unexpected results.
  • Forgetting to calculate the OFFSET correctly, leading to repeated or skipped records.
  • Not escaping output, which can cause security issues.
  • Not handling the case when the page number is out of range (less than 1 or greater than total pages).
php
<?php
// Wrong: No validation of page number
$page = $_GET['page']; // Could be anything

// Right: Validate page number
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) {
    $page = 1;
}
// Also check if $page > $total_pages after calculation
?>
📊

Quick Reference

  • Get current page: $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
  • Calculate offset: $offset = ($page - 1) * $items_per_page;
  • SQL query: SELECT * FROM table LIMIT $items_per_page OFFSET $offset;
  • Total pages: $total_pages = ceil($total_records / $items_per_page);
  • Generate links: Loop from 1 to $total_pages and create links.

Key Takeaways

Use SQL LIMIT and OFFSET to fetch only the records for the current page.
Always validate and sanitize the page number from user input.
Calculate total pages by dividing total records by items per page and rounding up.
Generate clear navigation links so users can switch pages easily.
Handle edge cases like page numbers less than 1 or greater than total pages.