What are the potential pitfalls to avoid when implementing a "next" and "previous" functionality for a gallery in PHP?

Potential pitfalls to avoid when implementing a "next" and "previous" functionality for a gallery in PHP include not properly handling edge cases such as the first and last images, not sanitizing user input to prevent SQL injection, and not checking for valid image IDs before displaying them.

// Check if the current image is the first one
if($currentImageId == 1){
    $prevImageId = $totalImages; // Set the previous image ID to the last image
} else {
    $prevImageId = $currentImageId - 1; // Set the previous image ID to the previous one
}

// Check if the current image is the last one
if($currentImageId == $totalImages){
    $nextImageId = 1; // Set the next image ID to the first image
} else {
    $nextImageId = $currentImageId + 1; // Set the next image ID to the next one
}

// Sanitize user input to prevent SQL injection
$currentImageId = intval($_GET['imageId']);

// Check if the image ID is valid before displaying it
if($currentImageId > 0 && $currentImageId <= $totalImages){
    // Display the image
} else {
    // Display an error message or redirect to a default image
}