What are common pitfalls when using PHP for creating a gallery with pagination?

One common pitfall when creating a gallery with pagination in PHP is not properly handling the pagination logic, which can lead to displaying incorrect results or breaking the pagination functionality. To solve this, ensure that the pagination variables are correctly calculated based on the total number of items and the items per page.

<?php
// Set the number of items per page
$itemsPerPage = 10;

// Get the total number of items
$totalItems = // Get the total number of items from your database or source

// Calculate the total number of pages
$totalPages = ceil($totalItems / $itemsPerPage);

// Get the current page number
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// Calculate the starting item for the current page
$start = ($page - 1) * $itemsPerPage;

// Query your database to fetch items for the current page
$query = "SELECT * FROM gallery_items LIMIT $start, $itemsPerPage";
// Execute the query and display the items
?>