How can error handling be enhanced in the PHP code to better identify and troubleshoot database-related issues?

To enhance error handling in PHP code for database-related issues, you can utilize try-catch blocks to catch exceptions thrown by database operations. Within the catch block, you can log the error message and details to a file or display them for debugging purposes. Additionally, you can use functions like mysqli_error() to retrieve specific error messages from the database.

try {
    // Database connection and query execution
    $connection = new mysqli($host, $username, $password, $database);
    if ($connection->connect_error) {
        throw new Exception("Connection failed: " . $connection->connect_error);
    }
    
    // Perform database operations
    
} catch (Exception $e) {
    // Log or display the error message
    error_log("Database error: " . $e->getMessage());
}