How to Add Pagination in PHP (Limit & Offset Explained)
Pagination divides data into multiple pages.
👉 Instead of loading everything,
you load a small number per page.
Benefits:
better performance
faster loading
cleaner UI
1️⃣ Set items per page
$limit = 5; // items per page
2️⃣ Get current page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
3️⃣ Calculate offset
$offset = ($page - 1) * $limit;
4️⃣ Fetch data with LIMIT
$result = $conn->query("
SELECT * FROM gallery
ORDER BY id DESC
LIMIT $limit OFFSET $offset
");
5️⃣ Count total items
$total_result = $conn->query("SELECT COUNT(*) as total FROM gallery");
$total = $total_result->fetch_assoc()['total'];
6️⃣ Calculate total pages
$total_pages = ceil($total / $limit);
7️⃣ Create pagination links
for ($i = 1; $i <= $total_pages; $i++):
?>
<a href="?page=<?= $i ?>"
style="<?= $i == $page ? 'font-weight:bold;' : '' ?>">
<?= $i ?>
</a>
<?php endfor; ?>
🔥 Example URL
gallery.php?page=2
✨ Highlight current page
$i == $page
⚠️ Important Notes
always validate page number
prevent negative values
use LIMIT carefully
🔐 Security Tip
Cast page to integer:
(int)$_GET['page']
👉 prevents injection
🚀 Advanced Pagination
✔ Previous / Next
<?php if ($page > 1): ?>
<a href="?page=<?= $page - 1 ?>">Prev</a>
<?php endif; ?>
<?php if ($page < $total_pages): ?>
<a href="?page=<?= $page + 1 ?>">Next</a>
<?php endif; ?>
✔ Limit visible pages
// show only nearby pages
👉 improves UX
🔥 Key Features
efficient data loading
scalable structure
easy navigation
✅ Summary
To implement pagination:
set limit
get current page
calculate offset
query with LIMIT
generate links
🚀 Next Step
You can extend this by:
infinite scroll
AJAX pagination
load more button
Hope this helps 🚀
Login with Google