What are the best practices for error handling in PHP scripts, especially when dealing with database connectivity and migration issues?

When dealing with database connectivity and migration issues in PHP scripts, it is important to implement proper error handling to gracefully handle any potential errors that may arise. This includes using try-catch blocks to catch exceptions thrown by database operations, logging errors for debugging purposes, and providing informative error messages to users.

try {
    // Attempt to connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // Log the error
    error_log("Database connection failed: " . $e->getMessage());
    
    // Display a user-friendly error message
    echo "An error occurred while connecting to the database. Please try again later.";
}