What are the best practices for structuring PHP code to handle dynamic SQL queries based on user input, such as changing the WHERE clause based on dropdown selections?

When handling dynamic SQL queries based on user input, it is important to sanitize and validate the input to prevent SQL injection attacks. One approach is to use prepared statements with placeholders for user input values and dynamically construct the query based on the user's selections. This allows for flexibility in building the WHERE clause based on dropdown selections while ensuring the security of the application.

// Assuming $db is your database connection object

// Sanitize and validate user input
$dropdownSelection = isset($_POST['dropdown_selection']) ? $_POST['dropdown_selection'] : '';
$dropdownSelection = filter_var($dropdownSelection, FILTER_SANITIZE_STRING);

// Prepare the base SQL query
$sql = "SELECT * FROM table_name WHERE 1=1";

// Dynamically construct the WHERE clause based on user input
if ($dropdownSelection === 'option1') {
    $sql .= " AND column_name = 'value1'";
} elseif ($dropdownSelection === 'option2') {
    $sql .= " AND column_name = 'value2'";
}

// Prepare and execute the query
$stmt = $db->prepare($sql);
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Display results or handle them as needed