How can error handling be improved in PHP MySQL queries to troubleshoot issues like incorrect results?

When troubleshooting issues like incorrect results in PHP MySQL queries, error handling can be improved by using the mysqli_error() function to display detailed error messages when a query fails. This can help pinpoint the exact cause of the issue and make debugging easier.

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

if (!$result) {
    die("Error executing query: " . mysqli_error($conn));
}

// Process the query result here

mysqli_close($conn);