What best practices should be followed when handling database connections in PHP to avoid access denied errors?

When handling database connections in PHP, it's important to securely store and retrieve database credentials to avoid access denied errors. One best practice is to use environment variables to store sensitive information like database username and password, and then access these variables in your PHP script to establish the database connection.

<?php
// Set database credentials as environment variables
$host = getenv('DB_HOST');
$username = getenv('DB_USERNAME');
$password = getenv('DB_PASSWORD');
$database = getenv('DB_NAME');

// Create a database connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>