Pagination, Search and Filters in a PHP API with MySQL: Return Large Lists Without Slowing Down
Quick answer: To paginate a PHP API with MySQL, read page and limit from the query string, validate them (with a maximum limit) and compute OFFSET = (page - 1) * limit. Build search and filters with WHERE and PDO parameters, never by concatenating user text, and run a COUNT query for the total. Return the rows, the total and the number of pages as JSON.
When an API starts returning many rows from a table, loading everything at once slows the system down, uses more memory and hurts the user experience. That is why professional APIs use pagination, search and filters to control how much data comes back.
In a plain PHP API with MySQL, you can do it with query string parameters, SQL with LIMIT and OFFSET, and dynamic WHERE filters. This article builds an endpoint that returns paginated lists, supports text search and optional filters, and sends organized JSON to a frontend, an Android app, an admin panel or DataTables.
Why paginate an API?
Picture a table with 50,000 customers, products, orders or log entries. If the API returns all of them in one request, the server takes long to answer, the database works hard and the frontend may freeze trying to render it all.
Pagination splits the rows into smaller pieces. Page 1 returns rows 1 to 10, page 2 returns 11 to 20, and so on. The API responds faster, transfers less data and the frontend can navigate page by page.
Example URL with pagination, search and filters
/api/users?page=1&limit=10&search=jane&status=active
page: the current page;limit: how many rows per page;search: text to look for in name or email;status: filters active or inactive users.
The table used in the examples
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(150) NOT NULL,
email VARCHAR(150) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'active',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Reading and validating the parameters
<?php
$page = max(1, (int) ($_GET['page'] ?? 1));
$limit = (int) ($_GET['limit'] ?? 10);
$search = trim((string) ($_GET['search'] ?? ''));
$status = trim((string) ($_GET['status'] ?? ''));
if ($limit < 1) {
$limit = 10;
}
if ($limit > 100) {
$limit = 100; // never let a client ask for limit=100000
}
$offset = ($page - 1) * $limit;
The maximum limit is important: without it, anyone can call the API with limit=100000 and force the server to return far too much. As for the offset: with limit=10, page 1 gives offset 0, page 2 gives 10 and page 3 gives 20.
Building dynamic filters safely
Keep one array of SQL conditions you write yourself and another of values coming from the user:
<?php
$where = [];
$params = [];
if ($search !== '') {
// Escape LIKE wildcards typed by the user, so "50%" searches for "50%"
$term = '%' . addcslashes($search, '%_\\') . '%';
$where[] = '(name LIKE :search1 OR email LIKE :search2)';
$params[':search1'] = $term;
$params[':search2'] = $term;
}
if ($status !== '') {
if (!in_array($status, ['active', 'inactive'], true)) {
jsonResponse(422, [
'success' => false,
'message' => 'Invalid status.',
'errors' => ['status' => 'Use active or inactive.']
]);
}
$where[] = 'status = :status';
$params[':status'] = $status;
}
$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';
Only fixed SQL goes into $where; every value from the URL goes into $params. Using :search1 and :search2 instead of repeating one placeholder keeps the query working when PDO uses native prepared statements. See how to prevent SQL injection with PDO.
The main query with LIMIT and OFFSET
<?php
$sql = "
SELECT id, name, email, status, created_at
FROM users
{$whereSql}
ORDER BY id DESC
LIMIT :limit OFFSET :offset
";
$stmt = $pdo->prepare($sql);
foreach ($params as $key => $value) {
$stmt->bindValue($key, $value);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$users = $stmt->fetchAll();
limit and offset are bound with PDO::PARAM_INT; otherwise MySQL may receive them as quoted strings and reject the query.
Counting the total
The frontend also needs the total number of matching rows to know how many pages exist. The count must use the same filters:
<?php
$stmtTotal = $pdo->prepare("SELECT COUNT(*) FROM users {$whereSql}");
$stmtTotal->execute($params);
$total = (int) $stmtTotal->fetchColumn();
$totalPages = (int) ceil($total / $limit);
The JSON response
<?php
jsonResponse(200, [
'success' => true,
'data' => $users,
'pagination' => [
'page' => $page,
'limit' => $limit,
'total' => $total,
'total_pages' => $totalPages
]
]);
Example:
{
"success": true,
"data": [
{
"id": 15,
"name": "Jane Smith",
"email": "jane@example.com",
"status": "active",
"created_at": "2026-05-04 10:30:00"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 58,
"total_pages": 6
}
}
Complete endpoint
<?php
header('Content-Type: application/json; charset=utf-8');
function jsonResponse(int $statusCode, array $data): void
{
http_response_code($statusCode);
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
'user',
'password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]
);
$page = max(1, (int) ($_GET['page'] ?? 1));
$limit = min(100, max(1, (int) ($_GET['limit'] ?? 10)));
$search = trim((string) ($_GET['search'] ?? ''));
$status = trim((string) ($_GET['status'] ?? ''));
$offset = ($page - 1) * $limit;
$where = [];
$params = [];
if ($search !== '') {
$term = '%' . addcslashes($search, '%_\\') . '%';
$where[] = '(name LIKE :search1 OR email LIKE :search2)';
$params[':search1'] = $term;
$params[':search2'] = $term;
}
if ($status !== '') {
if (!in_array($status, ['active', 'inactive'], true)) {
jsonResponse(422, ['success' => false, 'message' => 'Invalid status.']);
}
$where[] = 'status = :status';
$params[':status'] = $status;
}
$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';
$stmt = $pdo->prepare("
SELECT id, name, email, status, created_at
FROM users
{$whereSql}
ORDER BY id DESC
LIMIT :limit OFFSET :offset
");
foreach ($params as $key => $value) {
$stmt->bindValue($key, $value);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$users = $stmt->fetchAll();
$stmtTotal = $pdo->prepare("SELECT COUNT(*) FROM users {$whereSql}");
$stmtTotal->execute($params);
$total = (int) $stmtTotal->fetchColumn();
jsonResponse(200, [
'success' => true,
'data' => $users,
'pagination' => [
'page' => $page,
'limit' => $limit,
'total' => $total,
'total_pages' => (int) ceil($total / $limit)
]
]);
} catch (Throwable $e) {
error_log('Error listing users: ' . $e->getMessage());
jsonResponse(500, [
'success' => false,
'message' => 'Internal error while reading the data.'
]);
}
Calling the API from the frontend
<script>
async function loadUsers(page = 1) {
const params = new URLSearchParams({
page,
limit: 10,
search: document.getElementById('search').value,
status: document.getElementById('status').value
});
const response = await fetch(`/api/users?${params}`);
const result = await response.json();
if (!response.ok) {
alert(result.message || 'Could not load users.');
return;
}
console.log(result.data); // rows for this page
console.log(result.pagination); // build previous/next buttons from this
}
</script>
URLSearchParams encodes every value for you, so search terms with spaces or & don't break the URL.
A response for DataTables
With DataTables in server-side mode, return draw, recordsTotal, recordsFiltered and data. Note that the two counts are different: recordsTotal is the table without filters and recordsFiltered is the count after search and filters.
<?php
$recordsTotal = (int) $pdo->query('SELECT COUNT(*) FROM users')->fetchColumn();
jsonResponse(200, [
'draw' => (int) ($_GET['draw'] ?? 1),
'recordsTotal' => $recordsTotal,
'recordsFiltered' => $total,
'data' => $users
]);
Filtering by a date range
<?php
function isValidDate(string $date): bool
{
$dt = DateTime::createFromFormat('Y-m-d', $date);
return $dt && $dt->format('Y-m-d') === $date;
}
$from = trim((string) ($_GET['from'] ?? ''));
$to = trim((string) ($_GET['to'] ?? ''));
if ($from !== '' && !isValidDate($from)) {
jsonResponse(422, [
'success' => false,
'message' => 'Invalid start date.',
'errors' => ['from' => 'Use the YYYY-MM-DD format.']
]);
}
if ($from !== '') {
$where[] = 'created_at >= :from';
$params[':from'] = $from . ' 00:00:00';
}
if ($to !== '' && isValidDate($to)) {
$where[] = 'created_at < :to';
$params[':to'] = (new DateTime($to))->modify('+1 day')->format('Y-m-d') . ' 00:00:00';
}
Using "less than the next day" for the end date includes the whole last day, even for timestamps with fractions of a second.
Safe dynamic sorting
Column names and sort directions can't be bound as parameters, so use an allowlist:
<?php
$orderBy = $_GET['order_by'] ?? 'id';
$orderDir = strtolower($_GET['order_dir'] ?? 'desc');
if (!in_array($orderBy, ['id', 'name', 'email', 'created_at'], true)) {
$orderBy = 'id';
}
if (!in_array($orderDir, ['asc', 'desc'], true)) {
$orderDir = 'desc';
}
$sql = "
SELECT id, name, email, status, created_at
FROM users
{$whereSql}
ORDER BY {$orderBy} {$orderDir}, id DESC
LIMIT :limit OFFSET :offset
";
Adding id as a final tiebreaker keeps the order stable: without it, rows with the same name can swap places between pages and appear twice or not at all.
Indexes make a real difference
If the API often filters or sorts by status, created_at or email, add indexes:
CREATE INDEX idx_users_status_created ON users (status, created_at);
CREATE INDEX idx_users_email ON users (email);
One caveat: a search like LIKE '%jane%', with a wildcard at the start, can't use a normal index and scans the table. For large tables, prefer prefix searches (LIKE 'jane%') or a MySQL FULLTEXT index.
Very large tables: cursor (keyset) pagination
OFFSET gets slower as pages go deeper, because MySQL still reads and discards every skipped row. For feeds, logs and infinite scroll, paginate by the last ID seen instead:
<?php
$afterId = (int) ($_GET['after_id'] ?? 0);
$sql = 'SELECT id, name, email FROM users'
. ($afterId > 0 ? ' WHERE id < :after_id' : '')
. ' ORDER BY id DESC LIMIT :limit';
$stmt = $pdo->prepare($sql);
if ($afterId > 0) {
$stmt->bindValue(':after_id', $afterId, PDO::PARAM_INT);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
$nextCursor = $rows ? end($rows)['id'] : null; // send it back as after_id
Each page is as fast as the first one. The trade-off: there is no "jump to page 37", only "next".
Common pagination mistakes in PHP
1. Returning the whole table
It works at first, then the API slows down as the data grows.
2. Not capping the limit
Without a maximum, anyone can make the API return thousands of rows.
3. Putting URL values straight into SQL
Values from $_GET go through prepared statements, and column names through an allowlist.
4. Forgetting the total
Without it, the frontend can't build full pagination controls.
5. No indexes
On large tables, filters without indexes make every request slow.
Checklist
- Does the API read
pageandlimit, with a maximum limit? - Is the offset computed correctly?
- Are filters optional, and is search done with prepared statements?
- Does the query return only the columns you need?
- Does the JSON include
dataandpagination? - Does the total use the same filters?
- Do sort columns go through an allowlist, with a stable tiebreaker?
- Do frequently filtered columns have indexes?
Conclusion
Pagination, search and filters are among the best ways to improve the performance and usability of a PHP API with MySQL. Instead of returning everything, the API delivers only what each screen needs.
With LIMIT, OFFSET, dynamic filters, prepared statements and a consistent JSON response, your endpoints become faster, safer and easier to integrate. For errors and status codes, see error handling in a PHP API.
Frequently asked questions about pagination in PHP APIs
Why not return every row at once?
It slows the API down, uses more memory and can freeze the frontend on large tables. Pagination returns one slice of the data per request.
What is the difference between LIMIT and OFFSET?
LIMIT sets how many rows to return; OFFSET sets how many rows to skip first.
How many rows per page should I use?
It depends on the screen, but 10, 20, 50 or 100 are common. Always set a maximum to prevent abuse.
How do I search by name or email in PHP?
Use LIKE with prepared statements on the name and email columns, escaping % and _ in the user's term.
Do I need to return the total count?
Yes, so the frontend can work out how many pages exist and build the pagination controls.
Does pagination improve performance?
Yes. Returning less data per request lightens the database, the server and the frontend. On large tables, also index the columns used for filtering and sorting.