How can one effectively handle error messages when executing MySQL queries in PHP?

When executing MySQL queries in PHP, it is important to handle error messages effectively to troubleshoot and debug any issues that may arise. One way to do this is by using the mysqli_error() function to retrieve the error message generated by the most recent MySQL operation. By checking for errors after each query execution, you can easily identify and address any issues in your code.

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

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

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

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

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

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