How can the SQL query be optimized to achieve the desired result of filtering products based on specific criteria?
To optimize the SQL query for filtering products based on specific criteria, you can use prepared statements to prevent SQL injection and improve performance. By using placeholders for the criteria values, you can dynamically bind them to the query and execute it efficiently.
// Assuming $criteria is an array containing the specific criteria for filtering
$criteria = [
'category' => 'Electronics',
'price' => 100
];
// Build the SQL query with placeholders for criteria
$sql = "SELECT * FROM products WHERE category = :category AND price <= :price";
// Prepare the SQL query
$stmt = $pdo->prepare($sql);
// Bind the criteria values to the placeholders
$stmt->bindParam(':category', $criteria['category']);
$stmt->bindParam(':price', $criteria['price']);
// Execute the query
$stmt->execute();
// Fetch the results
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display the filtered products
foreach ($products as $product) {
echo $product['name'] . ' - ' . $product['price'] . '<br>';
}