What are the best practices for setting the MySQL connection to UTF-8 in a PHP application?
When working with MySQL in a PHP application, it's important to ensure that the connection is set to use UTF-8 encoding to properly handle special characters and international text. This can be achieved by executing a query to set the connection charset to UTF-8 immediately after connecting to the database.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Set the connection charset to UTF-8
$mysqli->query("SET NAMES 'utf8'");
$mysqli->query("SET CHARACTER SET utf8");
$mysqli->query("SET character_set_connection=utf8");