How can the UTF-8 encoding be properly configured in a PHP MySQL connection to handle special characters?
When working with special characters in a PHP MySQL connection, it's important to configure the UTF-8 encoding to ensure proper handling of these characters. This can be done by setting the character set to UTF-8 in both the MySQL connection and the PHP script. By doing this, special characters will be stored and retrieved correctly from the database.
// Establish a MySQL connection with UTF-8 encoding
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->set_charset("utf8");
// Set UTF-8 encoding in PHP script
header('Content-Type: text/html; charset=utf-8');
mysqli_set_charset($mysqli, 'utf8');