In MySQLi, convert query errors into exceptions
P粉060528326
P粉060528326 2023-08-24 11:53:00
0
2
461

I'm trying to convert MySQLi query errors into exceptions, but it's not possible - the mysqli_sql_exception exception is only thrown when connecting to the database fails.

I used mysqli_report(MYSQLI_REPORT_STRICT) with a procedural MySQLi function embedded in a custom wrapper class.

Previous 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: No warning or exception is thrown when a query fails, is this normal? So I have to check if mysqli_query() returns false?

P粉060528326
P粉060528326

reply all (2)
P粉420958692

No.

You should be able to follow your requirements and instruct the mysqli driver to throw an exception on SQL errors, but you will need to enableMYSQLI_REPORT_ERRORif it is not already enabled....

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT)

mysqli_query()Should now throw an exception on error. You don't need to check the return value on failure (the exception will be thrown anyway).

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; }

(Note: I changed$this->SQLto$SQLin the rethrown exception.)

    P粉549412038

    Some time ago I successfully solved this problem. As pointed out inother answers,

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    is the correct way to tell mysqli to throw an exception.

    Just make surenot to wrap try-catchin every query. This is a very common misconception, once you start using exceptions you should start throwing try and catch everywhere. In contrast, try-catch should be used with caution. Although 99% of errors should not be handled on site but by a site-wide error handler. You can learn more about this topic from myPHP Error Reportingarticle.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!