What are best practices for initializing a database connection using PDO in PHP?
When initializing a database connection using PDO in PHP, it is important to follow best practices to ensure secure and efficient database interactions. One common best practice is to store database connection details in a separate configuration file to easily manage and update them. Additionally, using try-catch blocks for error handling and setting the PDO attribute to throw exceptions on errors can help in debugging and resolving issues.
<?php
// Database connection details
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
// Create a PDO instance
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}