How can error handling be improved when dealing with MySQL queries in PHP to avoid unexpected results?

When dealing with MySQL queries in PHP, error handling can be improved by checking for errors after each query execution and displaying relevant error messages to identify and resolve issues promptly. This can be achieved by using the mysqli_error() function to retrieve error messages and handle them appropriately in the code.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Execute a MySQL query
$query = "SELECT * FROM table";
$result = $mysqli->query($query);

// Check for query execution errors
if (!$result) {
    die("Query failed: " . $mysqli->error);
}

// Process the query result
while ($row = $result->fetch_assoc()) {
    // Process the data
}

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