How can you ensure that the data selected from a dropdown menu is correctly saved to a MySQL database in PHP?

To ensure that the data selected from a dropdown menu is correctly saved to a MySQL database in PHP, you need to capture the selected value from the dropdown menu using a form submission, sanitize the input to prevent SQL injection, and then insert the data into the database using a prepared statement.

// Assuming you have a form with a dropdown menu named 'dropdown' and a submit button
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $selectedValue = $_POST['dropdown']; // Capture the selected value from the dropdown menu
    // Sanitize the input to prevent SQL injection
    $selectedValue = mysqli_real_escape_string($connection, $selectedValue);
    
    // Prepare a SQL statement to insert the selected value into the database
    $query = "INSERT INTO table_name (column_name) VALUES (?)";
    $stmt = mysqli_prepare($connection, $query);
    mysqli_stmt_bind_param($stmt, 's', $selectedValue);
    mysqli_stmt_execute($stmt);
    
    // Close the statement and connection
    mysqli_stmt_close($stmt);
    mysqli_close($connection);
}