What are the best practices for extracting data from dropdowns and saving it to a database using PHP?

When extracting data from dropdowns and saving it to a database using PHP, it is essential to properly sanitize and validate the input to prevent SQL injection attacks. Additionally, ensure that the database connection is properly established and that the data is inserted into the correct table and columns.

// Assuming you have a form with a dropdown named 'dropdown' and a submit button
if(isset($_POST['submit'])){
    $selectedOption = $_POST['dropdown']; // Extract the selected option from the dropdown

    // Sanitize and validate the input
    $selectedOption = filter_var($selectedOption, FILTER_SANITIZE_STRING);

    // Establish a connection to the database
    $conn = new mysqli('localhost', 'username', 'password', 'database_name');

    // Check if the connection is successful
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    }

    // Insert the selected option into the database
    $sql = "INSERT INTO table_name (column_name) VALUES ('$selectedOption')";

    if($conn->query($sql) === TRUE){
        echo "Data inserted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close(); // Close the database connection
}