What best practices should be followed to ensure consistent character encoding when working with PHP and MySQL databases?

To ensure consistent character encoding when working with PHP and MySQL databases, it is important to set the character set and collation properly in both PHP and MySQL. This can be achieved by setting the character set in the MySQL connection, specifying the character set in the PHP script, and ensuring that the data is stored and retrieved using the same character set.

// Set character set in MySQL connection
$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->set_charset("utf8");

// Specify character set in PHP script
header('Content-Type: text/html; charset=utf-8');
mysqli_set_charset($mysqli, "utf8");

// Store and retrieve data using the same character set
mysqli_query($mysqli, "SET NAMES 'utf8'");
mysqli_query($mysqli, "SET CHARACTER SET utf8");
mysqli_query($mysqli, "SET character_set_connection=utf8");