Are there best practices for handling error messages and debugging in PHP when using MySQL queries?

When handling error messages and debugging in PHP when using MySQL queries, it is important to check for errors after executing each query and display meaningful error messages to aid in troubleshooting. One best practice is to use the mysqli_error() function to retrieve the error message from the last MySQL operation.

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

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

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

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

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Process data
}

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