Skip to content

PHP MySQL Pagination: 7 Steps to Build It Correctly

PHP MySQL Pagination: 7 Steps to Build It Correctly

Showing every database row at once can make a page slow to scan and difficult to use. PHP MySQL pagination splits a result set into manageable pages, while still letting visitors move through the full collection. The basic idea is straightforward, but reliable pagination also needs careful counting, input validation, consistent filters, and links that behave correctly at the boundaries.

This guide walks through the full design, from deciding the page size to testing empty results. It uses MySQLi concepts and focuses on safe, maintainable behavior rather than a snippet that only works for one URL.


What Is PHP MySQL Pagination?

A practical PHP MySQL pagination flow keeps the requested page, database slice, result count, and navigation links in agreement. If one part uses different filters or assumptions, users can land on an empty or repeated page.

Why divide results into pages?

A product list, archive, or directory may contain more records than a reader needs to see at once. Returning and rendering everything can consume unnecessary database, network, and browser resources. Pagination asks the database for a limited slice and gives the reader controls to reach other slices.

Pagination also gives users a sense of location: they can see which page they are on and how to continue. It is not a substitute for good search or filters, but it works well when people need to browse a known collection in sequence.

How page, limit, and offset work together

Three values describe a simple numbered pagination system. The page is the requested position, the limit is the maximum number of records shown per page, and the offset is how many matching records to skip before returning the next slice.

The calculation is: offset equals (page minus one) multiplied by limit. With a page size of 10, the first page starts at offset zero, the second at 10, and the third at 20. The limit and offset belong to the database query; the page number is the more convenient value to expose in a URL.

Plan the Pagination Inputs

Choose a page size deliberately

Pick a limit that suits the type of content and the layout. A compact directory may need fewer rows than a table of short records. Keep the chosen limit under server control or restrict it to a small allowlist; do not let an unrestricted URL parameter request an enormous result set.

Keep the size consistent between the count query, the data query, and the navigation calculation. If users can choose a page size, validate that choice and recalculate the total pages using the selected value.

PHP MySQL pagination workflow from validated page input to result navigation
PHP Pagination: The Core Flow

Validate the requested page

Query-string values arrive as external input. Treat the page parameter as untrusted even when a link on your own site generated it. Convert it to an integer only after checking that it is a sensible positive value, and use page one when it is missing or invalid.

After determining the total page count, clamp a page number that is larger than the last available page. When there are no matching records, handle the zero-page case explicitly instead of trying to create links to a nonexistent page.

Count Rows and Calculate the Page Total

Count the same filtered records

The total count should describe the same set of records as the page query. If the listing is filtered by category, search term, publication status, or access rules, apply equivalent conditions to the count. Otherwise the navigation may claim that pages exist even though the data query cannot return matching rows.

Use a count query rather than retrieving every row just to count them. For a filtered listing, bind filter values safely, and keep the filtering logic shared or carefully synchronized so the count and listing cannot drift apart during future edits.

Calculate the number of pages safely

Divide the number of matching rows by the page size and round upward. In PHP, the mathematical operation is commonly represented with ceil(total rows divided by limit). For example, a result count that is not evenly divisible by the limit still needs a final, partially filled page.

Guard against a page size of zero before dividing. If the count is zero, show an appropriate empty state; do not display a misleading range such as “1–10 of 0.” These small checks prevent warnings and confusing navigation.

Fetch a Page of Results Safely

Use LIMIT and OFFSET for the selected slice

MySQL supports limiting the rows returned and skipping an initial number of rows. The query should apply the same WHERE conditions as the count, use a deterministic ordering, and then apply the calculated limit and offset. Without an explicit order, rows can appear in a different sequence between requests, which makes page boundaries unreliable.

For example, order an archive by its creation date and a unique identifier as a tie-breaker. If several records share the same date, the unique second sort key gives the database a stable order. The query should select only the columns the page needs rather than fetching unnecessary data.

Bind values and keep SQL structure controlled

Use MySQLi prepared statements for user-provided filter values. A prepared statement keeps SQL structure separate from the values supplied for execution, which is a key defense against SQL injection. Bind values with the appropriate parameter types, and check that the number of bound variables matches the placeholders.

SQL identifiers and keywords, such as a column name or sort direction, generally cannot be supplied as ordinary bound values. If a listing allows sorting, map each allowed option to a fixed, developer-defined SQL fragment; never paste an arbitrary URL value into the query. Validate limit and offset as integers and follow the database driver's supported binding approach.

Show controls that match the current page

Previous should lead to the current page minus one, except on the first page, where it should be disabled or omitted. Next should lead to the current page plus one, except on the last page. Numbered links can show a compact window around the current page, along with first and last page links when useful.

Do not create a link for an invalid page or show a next link when no next page exists. Mark the current page in a way that is visible and programmatically understandable, such as an appropriate current-page attribute on the link or a non-link current-page label.

Preserve useful query parameters

When generating each page URL, preserve filters and search terms that define the current result set, while replacing the old page value rather than adding a second page parameter. Build query strings with a URL-encoding function instead of concatenating raw values. This avoids broken links when a search term contains spaces or special characters.

Keep URL generation in one small helper rather than duplicating string manipulation in several places. Test it with a URL that has no query string and one that already has multiple parameters. The generated links should preserve the user's active filter and contain exactly one valid page value.

Render Results and Navigation

Make the result range clear

For a non-empty result set, you can show the range being displayed and the overall match count. Calculate the first displayed position from the offset and the last from the smaller of offset plus limit and total rows. On an empty result, show a helpful message and avoid rendering page controls.

Escape database text before placing it in HTML. Pagination protects query behavior; it does not automatically make record content safe to display. Keep markup for the navigation separate from data rendering so that each can be tested and changed independently.

Make controls usable without a mouse

Use descriptive link text and a navigation landmark so assistive technology users can identify the page controls. Ensure the current page is distinguishable beyond color alone, and make focus styles visible for keyboard users. If the page is long, consider returning focus or scrolling sensibly after navigation in client-side implementations.

Ordinary links that load the selected page are robust and work without JavaScript. If you later add asynchronous loading, retain a usable fallback and announce updated results appropriately; avoid silently changing the content without telling assistive technology users.

Improve Performance for Larger Tables

Keep filtering and sorting efficient

Pagination limits how many rows the application returns, but the database may still need to examine many rows to find and order the requested slice. Index columns used by common filters and ordering where appropriate, then inspect actual query performance against realistic data. Index design depends on the schema and workload, so avoid adding indexes without measuring their impact.

Deep pages can be slower with offset-based pagination because the database may need to pass over earlier matching rows before returning the requested slice. For large or frequently changing datasets, consider cursor or keyset pagination, which continues from the last seen sort key instead of a large numeric offset.

Keep count work proportionate

An exact total count can be useful, but it may be expensive for complicated filters or large tables. Decide whether readers truly need the exact number of pages. Some interfaces can show “previous” and “more results” controls without calculating a full count on every request.

Cache counts only when the underlying data and freshness expectations make that safe. If records change between a count query and a later page query, the displayed total can briefly be stale; design the interface to handle that normal possibility gracefully.

Handle Common Errors

Check boundary cases

Test the first page, a middle page, the final page, a page beyond the final page, zero, a negative number, and non-numeric input. Also test an empty collection and a result count exactly divisible by the page size. Each case should have a predictable output and no undefined variables or divide-by-zero errors.

Watch for off-by-one mistakes: page numbers are usually one-based, while offsets are zero-based. Confirm that the first result on page two follows the last result on page one under the same stable ordering.

Inspect database and URL failures

When a query fails, use controlled error handling and log diagnostic details privately rather than showing database internals to visitors. Confirm that the count and data queries use matching filters, that the connection is valid, and that every placeholder has a corresponding bound value.

For URL issues, inspect the generated address after applying filters and changing pages. Duplicate parameters, lost search terms, and unencoded values often explain navigation failures that otherwise look like database problems.

Test and Maintain the Pagination

Use a repeatable test checklist

Try a small test dataset where you know the expected order and page boundaries. Verify that each record appears once as you move through the pages, that the displayed count is credible, and that sorting and filtering remain active after following a link.

Retest after changing the page size, adding a filter, or modifying the sort order. Pagination bugs often appear after a feature change because only the data query or only the count query was updated.

Separate responsibilities in the code

Keep input validation, count calculation, data retrieval, URL creation, and HTML output as distinct steps or functions. This makes it easier to reuse the logic and to identify which part is responsible when a test fails.

For a small page, a few clearly named variables may be enough. As the application grows, a reusable pagination component can accept the validated current page, page size, total count, and a URL-building callback without taking ownership of the database connection.

Code editor open on a developer's monitor
A developer checks source code while refining a web application. · Photo: Startup Stock Photos / Openverse (CC0)

FAQ

How do I create pagination in PHP with MySQL?

Count the filtered matching records, validate the requested page, calculate the offset, and fetch only the selected slice with a stable sort order. Then render links for the available pages.

How do I calculate the total number of pages?

Divide the matching row count by the positive page size and round upward. Handle a zero-result set explicitly and ensure the count uses the same filters as the data query.

How do I prevent SQL injection in pagination?

Use prepared statements for values such as search filters, validate page and limit as integers, and allowlist any dynamic sort columns or directions. Do not insert arbitrary request values into SQL.

What should happen when a page number is invalid?

Choose a documented fallback, commonly page one for missing or malformed input, and clamp values above the last page. If there are no results, show an empty state without page links.

Is LIMIT and OFFSET suitable for large tables?

It is often convenient for modest datasets and numbered navigation. For very deep pages or rapidly changing large collections, measure its performance and consider keyset pagination, which continues from a known sort key.


Conclusion

Reliable PHP MySQL pagination is more than adding a limit to a query. Match the count and data filters, validate the page input, use stable ordering, bind data values, and make navigation preserve the user's current context.

Start by testing the boundary cases with a small dataset, then measure performance with realistic data. If offset queries become costly as readers move deep into a large list, evaluate a cursor-based approach instead of simply increasing server limits.

Write a comment