What are some best practices for connecting PHP to a database using PDO and avoiding common pitfalls?
Issue: When connecting PHP to a database using PDO, it is important to properly handle errors and exceptions to avoid common pitfalls such as SQL injection attacks and insecure connections.
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}