0

Consider the following toy code:

<?php
$stmt = $my_sqli->prepare("UPDATE MyTable SET a=?, b=?, c=? WHERE x='whatever'");

if ($my_sqli->errno) {
    throw new Exception(print_r($my_sqli->error_list, true));  // Condtion 1
} else if ($stmt === false) {
    throw new Exception("There was an error ... good luck trying to find it!");  // Condition 2
}

When column c does not exist in MyTable, prepare() returns FALSE, as per the manual (Here: https://www.php.net/manual/en/mysqli.prepare.php).

I had hoped that when prepare failed, Condition 1 would trap the error and throw an informative exception, but it doesn't. Instead the error is trapped by Condition 2 because $my_sqli->errno is 0.

How can I get a meaningful description of the error that occurred when $my_sqli->prepare failed? I can't find anything in the manual (probably too obvious for me to spot it!)

See description above.

Mike
  • 11
  • 2
  • This depends on your mysqli error mode settings. Add `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` before your `mysqli_connect()` (or `new mysqli()`) command, and this will ensure that errors with your SQL queries are thrown as exceptions in PHP. In the most recent versions of PHP, this is the default anyway. – ADyson Nov 29 '22 at 16:36
  • Just enable mysqli error reporting and forget about any manual error checking. An exception will be raised whenever you have an error in SQL. – Dharman Nov 29 '22 at 16:39
  • 1
    P.S. Doing it your way, there's no reason why your second `Exception` couldn't include the mysqli error message same as the first one. You're in control of that. But as per my first comment there's really no need to do it the way you're doing anyway. – ADyson Nov 29 '22 at 16:39
  • BTW all pages in the manual (or at least the one you linked) show `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` in the code examples. Did you make sure that you also have it? – Dharman Nov 29 '22 at 16:42

0 Answers0