How can PHP developers effectively handle error handling and debugging when encountering issues with SQL queries in their code?

When encountering issues with SQL queries in PHP code, developers can effectively handle error handling and debugging by using the try-catch block to catch any exceptions thrown by the database connection or query execution. Additionally, developers can use the mysqli_error() function to retrieve detailed error messages from the MySQL database, helping to identify and resolve the issue quickly.

try {
    // Attempt to establish a connection to the database
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check for connection errors
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }

    // Execute SQL query
    $result = $conn->query("SELECT * FROM table");

    // Check for query execution errors
    if (!$result) {
        throw new Exception("Error executing query: " . $conn->error);
    }

    // Process query results

} catch (Exception $e) {
    // Handle any exceptions and display error messages
    echo "Error: " . $e->getMessage();
}

// Close the database connection
$conn->close();