What are the best practices for handling character encoding in PHP when dealing with MySQL databases?
When dealing with character encoding in PHP and MySQL databases, it is important to ensure that all components are using the same character set to prevent data corruption or display issues. One common best practice is to set the character encoding for both PHP and MySQL to UTF-8, which supports a wide range of characters and languages.
// Set the character encoding for PHP
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
// Set the character encoding for MySQL connection
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
$mysqli->set_charset('utf8');