In PHP, what are some effective ways to check for errors and troubleshoot issues related to database queries?

When dealing with database queries in PHP, it is essential to check for errors and troubleshoot any issues that may arise. One effective way to do this is by utilizing error handling techniques such as try-catch blocks and using functions like mysqli_error() to retrieve detailed error messages from the database.

// Example of checking for errors in a database query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);

if (!$result) {
    die("Error in query: " . mysqli_error($connection));
}

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

// Close the database connection
mysqli_close($connection);