What are the best practices for handling database connections in PHP scripts to avoid access denied errors?

To avoid access denied errors when handling database connections in PHP scripts, it is recommended to securely store database credentials in a separate configuration file outside the web root directory. This helps prevent unauthorized access to sensitive information. Additionally, it is good practice to use PDO (PHP Data Objects) or MySQLi extension for connecting to the database, as they offer better security features and support prepared statements to prevent SQL injection attacks.

<?php
// Include the database configuration file
include 'config.php';

// Create a PDO connection to the database
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}
?>