How can PHP be used to dynamically generate search results based on user-selected filters?
To dynamically generate search results based on user-selected filters using PHP, you can create a form with filter options (such as checkboxes, dropdowns, etc.) that allow users to select their preferences. When the form is submitted, PHP can process the selected filters and query a database or an external API to fetch relevant search results based on the user's selections. Finally, the PHP script can display the search results on the webpage.
<?php
// Assuming $filters is an array containing the user-selected filters
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Build SQL query based on user-selected filters
$sql = "SELECT * FROM products WHERE 1=1";
if (!empty($filters)) {
foreach ($filters as $filter) {
$sql .= " AND category = '$filter'";
}
}
// Execute query
$result = $conn->query($sql);
// Display search results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Product Name: " . $row["product_name"] . "<br>";
// Display other product details as needed
}
} else {
echo "No results found.";
}
$conn->close();
?>
Related Questions
- What are some best practices for handling URL manipulation in PHP to avoid similar issues in the future?
- How can variables be utilized to control the positioning of echo output within HTML code in PHP scripts?
- What are some best practices for validating user input, such as image dimensions, in PHP to prevent potential issues like oversized images?