Are there any best practices to follow when using dropdown menus to filter data in PHP queries?

When using dropdown menus to filter data in PHP queries, it is important to sanitize user input to prevent SQL injection attacks. One best practice is to use prepared statements to safely pass user input into the SQL query. Additionally, validate the selected option against a predefined list of acceptable values to ensure only valid input is used in the query.

// Assuming $conn is the database connection

// Sanitize and validate the selected option from the dropdown menu
$selectedOption = isset($_POST['dropdown']) ? $_POST['dropdown'] : '';
$validOptions = ['option1', 'option2', 'option3']; // Define valid options
if (!in_array($selectedOption, $validOptions)) {
    // Handle invalid input
}

// Prepare and execute the SQL query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $selectedOption);
$stmt->execute();
$result = $stmt->get_result();

// Fetch and display the results
while ($row = $result->fetch_assoc()) {
    // Display data
}

$stmt->close();
$conn->close();