What best practices should be followed when handling MySQL errors in PHP scripts?

When handling MySQL errors in PHP scripts, it is important to properly display error messages to assist in debugging and troubleshooting. This can be achieved by using the mysqli_error() function to retrieve the error message from the MySQL server and displaying it to the user or logging it for the developer. Additionally, it is recommended to use try-catch blocks to catch exceptions and handle errors gracefully.

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

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

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

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

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