How can errors be properly handled and displayed when working with mysqli queries in PHP?

To properly handle and display errors when working with mysqli queries in PHP, you can use the `mysqli_error()` function to retrieve the error message if a query fails. This can help in debugging and troubleshooting any issues that may arise during query execution.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Perform a query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);

// Check for errors
if (!$result) {
    echo "Error: " . $mysqli->error;
}

// Display results
while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row['name'] . "<br>";
}

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