What are some common attributes that can be set during the initialization of a PDO connection in PHP?
When initializing a PDO connection in PHP, there are several common attributes that can be set to customize the behavior of the connection. Some of these attributes include setting the error mode, setting the fetch mode, setting the default fetch mode, and setting the character set.
// Initialize PDO connection with custom attributes
$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);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
Related Questions
- How can PHP developers ensure that the page redirection is triggered only when a specific output is generated, without affecting other functionalities?
- What are the potential limitations of using cURL for downloading large files in PHP?
- How can PHP developers ensure that their code is compatible with different operating systems?