What are some best practices for error handling and messaging in PHP when querying a database?

When querying a database in PHP, it's important to handle errors gracefully and provide informative error messages to aid in debugging. One best practice is to use try-catch blocks to catch any exceptions that may occur during the database query process. Additionally, utilizing functions like mysqli_error() to retrieve specific error messages from the database can help pinpoint the issue.

try {
    // perform database query
    $result = mysqli_query($connection, $query);
    
    if(!$result) {
        throw new Exception(mysqli_error($connection));
    }

    // process query results
} catch (Exception $e) {
    // handle error gracefully
    echo "Error: " . $e->getMessage();
}