← Back to Chapters

PHP CRUD Class Pagination Method

? PHP CRUD Class Pagination Method

? Quick Overview

This topic explains how pagination is implemented inside a PHP CRUD class to efficiently retrieve large datasets by dividing records into manageable pages.

? Key Concepts

  • Pagination limits the number of records fetched per request
  • OFFSET determines where the record set begins
  • LIMIT controls how many records are returned
  • Prepared statements improve security

? Syntax / Theory

Pagination works by calculating an offset based on the current page number and the number of records per page. This offset is then used with SQL LIMIT.

? View Code Example
// PHP CRUD class with pagination method
conn = $db;
}

public function selectWithPagination($page = 1, $limit = 5) {
$offset = ($page - 1) * $limit;
$stmt = $this->conn->prepare("SELECT * FROM ".$this->table." LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $limit);
$stmt->execute();
$result = $stmt->get_result();
return $result->fetch_all(MYSQLI_ASSOC);
}
}

// Using the pagination method
$conn = new mysqli("localhost", "username", "password", "myDB");
$user = new User($conn);
$pageData = $user->selectWithPagination(2, 5);
foreach($pageData as $row) {
echo $row['id']." - ".$row['first_name']."
";
}
?>

? Live Output / Explanation

The code fetches five records starting from the second page. The calculated offset ensures only the required records are retrieved and displayed.

? Interactive Concept

Change the page number and limit values to observe how different record sets are loaded dynamically.

? Use Cases

  • User management dashboards
  • Product listings in e-commerce websites
  • Admin panels with large datasets
  • Search results pagination

✅ Tips & Best Practices

  • Always validate page and limit values
  • Display total pages for better navigation
  • Use indexes on large tables for performance

? Try It Yourself

  • Add sorting functionality to the pagination method
  • Create previous and next page buttons
  • Combine pagination with search filters
  • Experiment with different limits per page