Pagination divides large datasets into pages — showing 10 or 20 results per page instead of thousands at once. It is one of the most common requirements in PHP applications and one of the easiest to build correctly. This tutorial builds a complete pagination system with MySQL from scratch.
Table of Contents
How Pagination Works
The math is simple:
// Given:
$total_records = 150; // Total items in the database
$per_page = 10; // Items per page
$current_page = 3; // The page the user is viewing
// Calculate:
$total_pages = ceil($total_records / $per_page); // 15 pages
$offset = ($current_page - 1) * $per_page; // Skip 20 records (pages 1 and 2)
// MySQL query:
$sql = "SELECT * FROM posts ORDER BY created_at DESC LIMIT $per_page OFFSET $offset";
// Returns records 21–30 for page 3
Complete Pagination Function
<?php
class Pagination {
public int $total;
public int $perPage;
public int $currentPage;
public int $totalPages;
public int $offset;
public function __construct(int $total, int $perPage, int $currentPage) {
$this->total = $total;
$this->perPage = $perPage;
$this->currentPage = max(1, $currentPage);
$this->totalPages = max(1, (int) ceil($total / $perPage));
$this->currentPage = min($this->currentPage, $this->totalPages);
$this->offset = ($this->currentPage - 1) * $perPage;
}
public function hasPrevious(): bool { return $this->currentPage > 1; }
public function hasNext(): bool { return $this->currentPage < $this->totalPages; }
public function links(string $url_pattern = '?page={page}'): string {
if ($this->totalPages <= 1) return '';
$html = '<nav class="pagination"><ul>';
// Previous button:
if ($this->hasPrevious()) {
$prev = str_replace('{page}', $this->currentPage - 1, $url_pattern);
$html .= "<li><a href='$prev'>« Previous</a></li>";
}
// Page numbers (show up to 5 around current page):
$start = max(1, $this->currentPage - 2);
$end = min($this->totalPages, $this->currentPage + 2);
if ($start > 1) {
$html .= "<li><a href='" . str_replace('{page}', 1, $url_pattern) . "'>1</a></li>";
if ($start > 2) $html .= "<li><span>...</span></li>";
}
for ($i = $start; $i <= $end; $i++) {
$url = str_replace('{page}', $i, $url_pattern);
$active = $i === $this->currentPage ? ' class="active"' : '';
$html .= "<li{$active}><a href='$url'>$i</a></li>";
}
if ($end < $this->totalPages) {
if ($end < $this->totalPages - 1) $html .= "<li><span>...</span></li>";
$last = str_replace('{page}', $this->totalPages, $url_pattern);
$html .= "<li><a href='$last'>{$this->totalPages}</a></li>";
}
// Next button:
if ($this->hasNext()) {
$next = str_replace('{page}', $this->currentPage + 1, $url_pattern);
$html .= "<li><a href='$next'>Next »</a></li>";
}
return $html . '</ul></nav>';
}
}
Using the Pagination Class
<?php
require 'Pagination.php';
$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'user', 'pass');
$per_page = 10;
$current_page = (int) ($_GET['page'] ?? 1);
// Get total count (one query):
$total = (int) $pdo->query("SELECT COUNT(*) FROM posts WHERE status = 'published'")->fetchColumn();
// Create pagination object:
$pagination = new Pagination($total, $per_page, $current_page);
// Fetch current page records:
$stmt = $pdo->prepare(
"SELECT id, title, excerpt, created_at FROM posts WHERE status = 'published'
ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
);
$stmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $pagination->offset, PDO::PARAM_INT);
$stmt->execute();
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!-- Display posts: -->
<?php foreach ($posts as $post): ?>
<article>
<h3><?= htmlspecialchars($post['title']) ?></h3>
<p><?= htmlspecialchars($post['excerpt']) ?></p>
</article>
<?php endforeach; ?>
<p>Showing page <?= $pagination->currentPage ?> of <?= $pagination->totalPages ?>
(<?= $total ?> total results)</p>
<?= $pagination->links('?page={page}') ?>
Pagination with Search/Filter
// Preserve search query across page links:
$search = htmlspecialchars(trim($_GET['search'] ?? ''));
$page = (int) ($_GET['page'] ?? 1);
// Build URL pattern that includes search:
$url_pattern = '?search=' . urlencode($search) . '&page={page}';
echo $pagination->links($url_pattern);
// Query with search + pagination:
$stmt = $pdo->prepare(
"SELECT COUNT(*) FROM posts WHERE title LIKE :search"
);
$stmt->execute([':search' => "%$search%"]);
$total = (int) $stmt->fetchColumn();
$pagination = new Pagination($total, $per_page, $page);
$stmt = $pdo->prepare(
"SELECT * FROM posts WHERE title LIKE :search
ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
);
$stmt->bindValue(':search', "%$search%");
$stmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $pagination->offset, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Laravel Pagination
In Laravel, pagination is handled automatically by Eloquent:
// Controller:
$posts = Post::where('status', 'published')
->orderBy('created_at', 'desc')
->paginate(10); // Returns a LengthAwarePaginator
return view('posts.index', compact('posts'));
// Blade template:
@foreach ($posts as $post)
<h3>{{ $post->title }}</h3>
@endforeach
{{ $posts->links() }} {{-- Renders Bootstrap pagination by default --}}
Frequently Asked Questions
Should I use LIMIT/OFFSET or cursor-based pagination?
LIMIT/OFFSET works well for most applications. For large datasets (100,000+ rows) or real-time data, cursor-based pagination (using the last seen ID or timestamp as the cursor) is more efficient because OFFSET requires MySQL to scan all preceding rows. Use cursor pagination for infinite scroll feeds; use LIMIT/OFFSET for traditional page navigation.
How do I prevent negative or too-large page numbers?
Always sanitize: $page = max(1, min((int)($_GET['page'] ?? 1), $total_pages)); — this clamps the page number between 1 and the last page. The Pagination class handles this in its constructor.
Conclusion
PHP pagination requires three things: a COUNT query for total records, a SELECT query with LIMIT and OFFSET, and page link generation. The Pagination class above handles all edge cases — first/last page logic, truncated page ranges, preserving query parameters in URLs. In Laravel, ->paginate() handles everything automatically including Bootstrap-styled links.
Next Step for Your Project Journey
Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

