What are best practices for dynamically building MySQL queries in PHP when dealing with select box values?

When dynamically building MySQL queries in PHP based on select box values, it is important to sanitize and validate user input to prevent SQL injection attacks. One approach is to use prepared statements with placeholders for dynamic values in the query. Additionally, it is recommended to use conditional logic to construct the query based on the selected values from the select boxes.

// Assume $conn is the MySQL database connection object

// Sanitize and validate select box values
$selectedValue1 = isset($_POST['select_box_1']) ? $_POST['select_box_1'] : '';
$selectedValue2 = isset($_POST['select_box_2']) ? $_POST['select_box_2'] : '';

// Build the base query
$query = "SELECT * FROM table_name WHERE 1=1";

// Add conditions based on select box values
if (!empty($selectedValue1)) {
    $query .= " AND column_name1 = ?";
}

if (!empty($selectedValue2)) {
    $query .= " AND column_name2 = ?";
}

// Prepare the statement
$stmt = $conn->prepare($query);

// Bind parameters
if (!empty($selectedValue1)) {
    $stmt->bind_param("s", $selectedValue1);
}

if (!empty($selectedValue2)) {
    $stmt->bind_param("s", $selectedValue2);
}

// Execute the query
$stmt->execute();

// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process the results
}

// Close the statement and connection
$stmt->close();
$conn->close();