How can PDO be utilized to set the character encoding for a MySQL database connection in PHP?

When establishing a connection to a MySQL database using PDO in PHP, it is important to set the character encoding to ensure that data is stored and retrieved correctly. This can be done by including the charset parameter in the DSN (Data Source Name) string when creating the PDO object.

// Set the character encoding for the MySQL database connection using PDO
$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);
    echo "Connected to the database successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}