How can WHERE conditions be utilized to accurately display images based on user input in PHP?

To accurately display images based on user input in PHP, WHERE conditions can be utilized in SQL queries to filter the images based on specific criteria such as user input or image categories. By using WHERE conditions, the query can be tailored to fetch only the images that match the specified criteria, ensuring that the displayed images are relevant to the user's input.

<?php
// Assuming $userInput contains the user's input
$userInput = $_POST['user_input'];

// Establish a database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and execute SQL query with WHERE condition
$sql = "SELECT * FROM images WHERE category = '$userInput'";
$result = $conn->query($sql);

// Display images based on query results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<img src='" . $row['image_path'] . "' alt='" . $row['image_alt_text'] . "'>";
    }
} else {
    echo "No images found.";
}

// Close database connection
$conn->close();
?>