What are the best practices for implementing a filter for image categories in PHP?

When implementing a filter for image categories in PHP, it is important to sanitize user input to prevent SQL injection and validate the input to ensure it matches the expected format. Additionally, it is recommended to use prepared statements when interacting with a database to avoid security vulnerabilities.

// Sanitize and validate the input
$category = filter_input(INPUT_POST, 'category', FILTER_SANITIZE_STRING);
if (!in_array($category, ['landscape', 'portrait', 'nature'])) {
    // Handle invalid input
}

// Use prepared statements to interact with the database
$stmt = $pdo->prepare("SELECT * FROM images WHERE category = :category");
$stmt->bindParam(':category', $category);
$stmt->execute();

// Process the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Display or process the image data
}