What are some recommended options to set when establishing a PDO connection in PHP?

When establishing a PDO connection in PHP, it is important to set some recommended options to ensure a secure and efficient connection. Some of these options include setting the error mode to PDO::ERRMODE_EXCEPTION to handle errors as exceptions, setting the default fetch mode to PDO::FETCH_ASSOC for fetching data as associative arrays, and setting the character set to ensure proper encoding of data.

// Establishing a PDO connection with recommended options
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
];

try {
    $pdo = new PDO($dsn, $username, $password, $options);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}