What are the recommended methods for setting character encoding in MySQL queries when using PHP, and why is it important for data integrity?
When working with MySQL queries in PHP, it is important to set the character encoding to ensure data integrity. This can be done by using the mysqli_set_charset function to specify the character set for the connection. By setting the character encoding properly, you can avoid issues with data corruption or incorrect display of special characters.
// Set character encoding for MySQL connection
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Set character encoding to UTF-8
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
}