PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
163: Building a Pagination Component from Scratch
I've always found pagination a bit tedious. The basic math is simple, but getting the "edges" right—like what happens when a user manually types page 999 into the URL—is where most developers trip up. Today, we're going to build a pagination component for a product review system. Instead of using a library, we'll build it from scratch so you actually understand the logic flowing through the request.
Calculating the window of data
First, we need to figure out which slice of our data to show. I'm assuming we have a total count of records and a set limit for how many we want per page. I usually start by grabbing the current page from the $_GET superglobal, but since that's user input, I'm casting it to an integer immediately.
$reviewsPerPage = 5;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
// Let's assume we queried the DB and got 23 total reviews
$totalReviews = 23;
$totalPages = ceil($totalReviews / $reviewsPerPage);
$offset = ($currentPage - 1) * $reviewsPerPage;
The ceil() function is key here. If we have 23 reviews and 5 per page, we need 5 pages, even though the last page only has 3 items. If we used floor(), those last three reviews would effectively vanish from the site.
Generating the navigation links
Now we need the HTML. I don't want to just list every single page number if we have 100 pages—that would wreck the UI. For this example, we'll keep it simple and loop through the total pages, but I'll wrap them in a way that allows us to highlight the active page.
<div class="pagination">
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
<a href="?page="
class="">
</a>
<?php endfor; ?>
</div>
Fixing the "Ghost Page" bug
Here is where I usually make my first mistake. I just tested the code above, and I realized that if I manually type ?page=999 in the browser, the page loads, but the "active" class is applied to a page that doesn't exist, and the content area is empty. It looks broken to the user.
We can't trust the $_GET['page'] value just because we cast it to an integer. We need to constrain it between 1 and the $totalPages. I'll add a check right after I calculate the total pages to "clamp" the value.
// The fix: Ensure the page is within valid bounds
if ($currentPage < 1) {
$currentPage = 1;
} elseif ($currentPage > $totalPages) {
$currentPage = $totalPages;
}
// Now recalculate the offset based on the corrected page
$offset = ($currentPage - 1) * $reviewsPerPage;
Now, if a user tries to go to page 999, the system gracefully pushes them back to the last available page. It's a small detail, but it's the difference between a professional component and a hobbyist script.
Wrapping it into a reusable component
Hardcoding this logic into every page is a nightmare. I prefer to wrap this into a function that returns the HTML string. This way, we can pass in the current page and total pages, and let the function handle the loop and the active state logic.
function renderPagination($totalPages, $currentPage) {
if ($totalPages <= 1) return ''; // No need for pagination if there's only one page
$html = '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
$activeClass = ($i == $currentPage) ? ' class="active"' : '';
$html .= "<a href='?page={$i}'{$activeClass}>{$i}</a> ";
}
$html .= '</div>';
return $html;
}
By separating the calculation (the offset) from the presentation (the HTML), you can now use this across your entire app regardless of whether you're paginating reviews, users, or blog posts.
📋 Practical Task
Exercise: Implement "Previous" and "Next" Controls
The current pagination component only shows numbers. To improve the user experience, you need to add "Prev" and "Next" buttons to the renderPagination function.
- Modify the function so that a "Prev" link appears only if the current page is greater than 1.
- Modify the function so that a "Next" link appears only if the current page is less than the total number of pages.
- Ensure these links correctly calculate the page number (e.g.,
$currentPage - 1). - Test your implementation by simulating a request for page 1 and page 5 (assuming 5 total pages) to ensure the buttons appear and disappear correctly.
There are no comments for now.