What are the best practices for handling character encoding and collation settings in MySQL databases for PHP applications?

When working with MySQL databases in PHP applications, it is important to properly handle character encoding and collation settings to ensure data consistency and avoid potential issues with special characters. To do this, it is recommended to set the character set and collation at the database, table, and column levels to match the encoding used in your application. This can be done using SQL queries or by configuring the connection settings in your PHP code.

// Set character encoding and collation for MySQL connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Set character set and collation
$conn->set_charset("utf8mb4");
$conn->query("SET collation_connection = 'utf8mb4_unicode_ci'");