使用php处理mysql错误的正确方法是什么?

What is the "proper" way to deal with errors when manipulating a sql database with php?

What Im currently doing looks like this:

$connection = new mysqli('hostname', 'user', 'pass', 'database');

if ($connection->connect_errno) {
    reportError("DB_CONNECTION_ERROR", $connection->connect_errno, $connection->connect_error);
displayError("DB_CONNECTION_ERROR");
}

$stmt = $connection->stmt_init();
$q = "query";

$stmt->prepare($q);
$stmt->bind_param('s', $username);
$stmt->execute();

reportError() is part of an error handling file I wrote and logs the error in a database

displayError() is part of the same file and tells the page what to display (as opposed to displaying the actual error).

However Im not sure of how to check for other errors, such as whether a statement was successfully prepared or whether a query was successful. Any recommendations appreciated!

Don't you find it quite odd to write database connection errors... into database?

I see also no point in having custom displayError() function. It should be generic _503() function, sending corresponding header along with general excuses.

I see no point in having custom logError() function either. PHP quite capable to log errors itself. trigger_error() serves me best.

Im not sure of how to check for other errors, such as whether a statement was successfully prepared

Ah, this one. Exceptions.

Mysqli should throw an exception if something went wrong. See mysqli_sql_exception for more details.

In your client code, you can then wrap your code in try/catch blocks:

try {

} catch (Exception $e) {

}

Sometimes, there are exceptions that can't be solved within a try/catch block, for example, the database server is down, and a site that is heavily reliant on the database would not be able to function anyway.

For those very critical problems, you can allow the exception to bubble upwards. You should then set an exception handler at the beginning of your script to catch those exceptions, notify the administrator and do some logging, then display an 500 error page to the user.