Turning query errors to Exceptions in MySQLi [duplicate]
Solution 1:
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
Solution 2:
do I have to check if mysqli_query() returned false?
No.
You should be able to do what you require and instruct the mysqli driver to throw exceptions on SQL errors, but you will need to enable MYSQLI_REPORT_ERROR
if it is not already....
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT)
mysqli_query()
should now throw exceptions on error. You do not need to check the return value for failure (which won't happen anyway because an exception is thrown).
public function mysqlQuery($SQL) {
try {
$this->Result = mysqli_query($this->DBlink, $SQL);
} catch (mysqli_sql_exception $e) {
throw new MySQLiQueryException($SQL, $e->getMessage(), $e->getCode());
}
return $this->Result;
}
(NB: I changed $this->SQL
to $SQL
in the re-thrown exception.)
Solution 3:
I know it's a little too late, but for the sake of posterity. I find MYSQLI_REPORT_STRICT to be to restrictive, certain exceptions where not be raised and hence they could not be handled by the catch block.
mysqli_report(MYSQLI_REPORT_ALL); // Traps all mysqli error
try {
$mysqli = new mysqli('localhost','user,'pwd','db');
/* I don't need to explicitly throw an exception as this is being
done automatically */
} catch(Exception $e) {
echo $e->getMessage();
}