What are best practices for error handling in MySQLi queries in PHP?

When executing MySQLi queries in PHP, it is important to handle errors properly to ensure the stability and security of your application. One best practice is to check for errors after each query execution and handle them appropriately, such as displaying an error message to the user or logging the error for debugging purposes.

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

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

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

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

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

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