What are the best practices for error handling and debugging in PHP scripts to identify and resolve database connection issues efficiently?

When encountering database connection issues in PHP scripts, it is essential to implement proper error handling and debugging techniques to identify and resolve the problem efficiently. One of the best practices is to enable error reporting and display detailed error messages during development, which can help pinpoint the root cause of the issue. Additionally, using try-catch blocks to catch exceptions and logging errors to a file can aid in troubleshooting database connection problems.

<?php

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Attempt to establish a connection
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// Log errors to a file
file_put_contents('error.log', $e->getMessage(), FILE_APPEND);

?>