How can dynamic SQL queries be generated in PHP to filter data based on user-selected options in a more flexible manner?
Dynamic SQL queries can be generated in PHP by constructing the query string based on user-selected options. This allows for more flexibility in filtering data as users can choose different options to customize their search criteria. By using PHP variables to hold user-selected options and concatenating them into the SQL query, you can dynamically adjust the query based on user input.
// User-selected filter options
$option1 = $_POST['option1'];
$option2 = $_POST['option2'];
// Start building the SQL query
$sql = "SELECT * FROM table_name WHERE 1=1";
// Add filters based on user-selected options
if (!empty($option1)) {
$sql .= " AND column1 = '$option1'";
}
if (!empty($option2)) {
$sql .= " AND column2 = '$option2'";
}
// Execute the query
$result = mysqli_query($conn, $sql);
// Fetch and display results
while ($row = mysqli_fetch_assoc($result)) {
// Display results
}