In the context of PHP, what are the best practices for handling MySQL query errors and displaying relevant error messages to the user?
When executing MySQL queries in PHP, it is important to handle errors effectively to provide meaningful feedback to the user. One common practice is to use the `mysqli_error()` function to retrieve the error message generated by the most recent MySQL query. This message can then be displayed to the user to help them understand what went wrong.
// Connect to MySQL database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute MySQL query
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
// Check for errors
if (!$result) {
die("Error: " . mysqli_error($conn));
}
// Display query results to the user
while ($row = mysqli_fetch_assoc($result)) {
echo "User: " . $row['username'] . "<br>";
}
// Close connection
mysqli_close($conn);