How can error handling be improved in PHP when executing SQL queries to troubleshoot issues with variable passing?

When executing SQL queries in PHP, it is important to properly handle errors that may occur during the query execution. One way to improve error handling is by using try-catch blocks to catch any exceptions thrown during the query execution. This allows for more detailed error messages to be displayed, making it easier to troubleshoot issues with variable passing.

try {
    // Your SQL query here
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception($conn->error);
    }
    
    // Process the query result
} catch (Exception $e) {
    echo "Error executing query: " . $e->getMessage();
}