How can conditional statements in PHP be effectively used to filter and retrieve specific data from a MySQL database based on user selections?

To filter and retrieve specific data from a MySQL database based on user selections, conditional statements in PHP can be used to dynamically construct SQL queries. By using if statements to check the user selections and appending appropriate conditions to the SQL query, you can effectively filter the data returned from the database.

// Assuming user selections are stored in variables $category, $price, and $rating

// Start building the SQL query
$sql = "SELECT * FROM products WHERE 1=1";

// Check if category is selected
if ($category != 'all') {
    $sql .= " AND category = '$category'";
}

// Check if price range is selected
if ($price != 'all') {
    $sql .= " AND price <= $price";
}

// Check if rating is selected
if ($rating != 'all') {
    $sql .= " AND rating >= $rating";
}

// Execute the SQL query and fetch the results
$result = mysqli_query($conn, $sql);

// Process the retrieved data
while ($row = mysqli_fetch_assoc($result)) {
    // Display or process the data as needed
}