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
}
Related Questions
- What potential issue might arise when using the "AND" keyword instead of a comma in a SQL query in PHP?
- In what scenarios would it be useful to calculate how many times a script can be executed within a specified time frame, and what considerations should be taken into account?
- In what scenarios would using a while loop with an incremental variable be more efficient than a for loop for generating a counter in PHP?