What are the best practices for building a database connection in PHP?
When building a database connection in PHP, it is important to follow best practices to ensure security, efficiency, and maintainability. One common approach is to use PDO (PHP Data Objects) to connect to the database, as it provides a secure and flexible way to interact with different database systems. It is also recommended to store database credentials in a separate configuration file outside of the web root to prevent unauthorized access.
// Database configuration
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
// Establish database connection using PDO
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) {
echo "Connection failed: " . $e->getMessage();
}