What steps can be taken to handle errors more effectively when using mysqli queries in PHP?

When using mysqli queries in PHP, it is important to handle errors effectively to ensure the stability and security of your application. One way to do this is by checking for errors after each query execution and displaying or logging them appropriately. This can help you identify and fix any issues that may arise during database interactions.

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

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

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

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

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

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