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

When executing MySQL queries in PHP, it is essential to implement proper error handling to catch any potential issues that may arise during the query execution. One common practice is to use try-catch blocks to capture exceptions thrown by the database operations and handle them accordingly. Additionally, utilizing functions like mysqli_error() to retrieve detailed error messages can help in diagnosing and resolving any issues with the queries.

<?php
// Establish a database connection
$connection = mysqli_connect("localhost", "username", "password", "database");

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

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

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

// Process the query results
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}

// Close the connection
mysqli_close($connection);
?>