What are the best practices for establishing a connection to a database using PHP Data Objects (PDO)?
Establishing a connection to a database using PHP Data Objects (PDO) involves creating a new PDO object with the database credentials such as the database type, host, database name, username, and password. It is important to handle potential connection errors by wrapping the connection code in a try-catch block and throwing an exception if an error occurs. Additionally, setting the PDO error mode to exception can help in debugging connection issues.
<?php
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>