Skip to Content
Course content

163: Building a Pagination Component from Scratch

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.