Search code examples
phpmysqli

Turning query errors to Exceptions in MySQLi


I'm trying to turn MySQLi query errors to Exceptions, but couldn't - mysqli_sql_exception is thrown only if it failed to connect the DB.

I used mysqli_report(MYSQLI_REPORT_STRICT) and procedural MySQLi functions embedded to custom wrapper class.

Former code:

$result = mysqli_query($DBlink, $SQL);
if($result === false) {
    throw new MySQLiQueryException($SQL, mysqli_error($DBlink), mysqli_errno($DBlink));
}

Question: Is it normal no Warning, nor Exception are thrown when query fails so I have to check if mysqli_query() returned false?


Solution

  • Some time ago I managed to sort this matter out. As it was pointed out in the other answer,

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    

    is a correct way to tell mysqli to throw exceptions.

    Just make sure you don't wrap every query in a try-catch. This is a very common misconception that as soon as you started using exceptions you should start throwing tries and catches left and right. Quite contrary, try-catch should be used warily. While 99% of your errors shouldn't be handled in place, but rather by a site-wide error handler. You may read more on the topic from my article on PHP error reporting