What are best practices for error handling in PHP when using MySQL queries?

When handling errors in PHP with MySQL queries, it is important to check for errors after executing each query using functions like `mysqli_error()` or `mysqli_errno()`. It is also recommended to use prepared statements to prevent SQL injection attacks and improve error handling. Additionally, logging errors to a file or displaying them in a user-friendly manner can help in debugging and troubleshooting.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check for connection errors
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Execute MySQL query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Check for query errors
if (!$result) {
    die("Query failed: " . mysqli_error($connection));
}

// Fetch results
while ($row = mysqli_fetch_assoc($result)) {
    // Process results
}

// Close connection
mysqli_close($connection);