What are some best practices for handling character encoding and collation in PHP when working with database fields?

When working with database fields in PHP, it's important to ensure that character encoding and collation are properly set to avoid issues with data integrity and display. One best practice is to set the character encoding for the database connection to UTF-8, which supports a wide range of characters. Additionally, make sure that the collation for database fields is also set to a UTF-8 collation to ensure consistency in sorting and comparing strings.

// Set character encoding and collation for database connection
$dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8';
$username = 'username';
$password = 'password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);

// Connect to the database
try {
    $pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}