What are the best practices for error handling and debugging when working with MySQL queries in PHP?

When working with MySQL queries in PHP, it is important to implement proper error handling and debugging techniques to catch and troubleshoot any issues that may arise. One common practice is to use the `mysqli_error()` function to display detailed error messages when a query fails. Additionally, using `mysqli_report(MYSQLI_REPORT_ERROR)` can help to automatically throw exceptions for errors, making it easier to handle them in your code.

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

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

// Set mysqli to throw exceptions for errors
mysqli_report(MYSQLI_REPORT_ERROR);

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

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

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

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