When using PDO in PHP, what are the best practices for setting the database connection to UTF-8?
When using PDO in PHP, it's important to set the database connection to UTF-8 to ensure proper handling of character encoding. This can be achieved by setting the charset option to utf8 in the DSN string when creating the PDO connection. This will ensure that data is stored and retrieved in UTF-8 encoding, preventing any potential encoding issues.
$dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}