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:
public function mysqlQuery($SQL) {
$this->Result = mysqli_query($this->DBlink, $SQL);
if($this->Result === false)
throw new MySQLiQueryException($SQL, mysqli_error($this->DBlink), mysqli_errno($this->DBlink));
return $this->Result;
}
Question: Is it normal no Warning, nor Exception are thrown when query fails so I have to check if mysqli_query() returned false?
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.
However, if you are wrapping mysqli functions in your own wrapper (as everyone should!) - it doesn't make too much difference. Either way you will need to add a code to check for success - be it if
or catch
. Yet there will be very limited number of calls, so, it wouldn't make too much trouble.
But all these folks who are "moving" from mysql to mysqli due to all that movement craze (but leaving the approach the same and having mysqli functions all over the code), will benefit from this setting dramatically (if they won't follow the common habit of wrapping every function call into try-catch, which would be useless).
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.)
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();
}