What could be causing incorrect encoding of special characters like umlauts when writing to a MySQL database using PHP?

Special characters like umlauts may be incorrectly encoded when writing to a MySQL database using PHP due to mismatched character encodings between the PHP script and the database. To solve this issue, you can set the character set for the connection to the database to ensure proper encoding of special characters.

// Establish a connection to the MySQL database with the correct character set
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");

// Insert data into the database with special characters properly encoded
$data = "Müller";
$sql = "INSERT INTO table_name (column_name) VALUES ('$data')";
$conn->query($sql);

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