8

There is a function in mysqli, called mysqli_report(), which looks like a counterpart for PDO's setAttribute() method with its ERRMODE_* constants. The manual says:

MYSQLI_REPORT_STRICT Throw mysqli_sql_exception for errors instead of warnings

So, having PDO::ERRMODE_EXCEPTION in mind, i tried this code

mysqli_report(MYSQLI_REPORT_STRICT);
$mysqli->query("foo");

but, to my disappointment, it produced no exception nor warning at all.

So, here goes the question: is there a way to tell mysqli to throw exceptions without using MYSQLI_REPORT_ALL?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

2 Answers2

15

For some reason people tend do use this post as a dupe target for the questions related to error reporting with mysqli. This answer never has been intended for the purpose.

Here is the correct answer in case you were directed here: What to do if your mysqli interaction failed

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
11

That's not a bug, that's a feature. ;)

PHP does not report mysqli or PDO errors by default because that information is highly sensitive, displaying it to a user is a great way to learn how to inject malicious data.

MYSQLI_REPORT_ERROR tells it to turn on the errors and MYSQLI_REPORT_STRICT tells it to convert those errors into Exceptions. This will give you a full report of the error message, so if you do this in production make sure that you do not display it to the end user.

Using the Pipe symbol | allows you to set multiple constants in most of PHPs methods and functions. PDO, mysqli, filter_var, etc. all use the pipe to set multiple optional arguments of the same type, or a "bitwise disjunction of flags" to use the fancy term for it. The lazy person's array argument.

Michael Ryan Soileau
  • 1,763
  • 17
  • 28
  • 5
    Discouraging one from reporting errors by default (especially as exceptions) is really misguidance. With `display_errors` turned off, errors, warnings and uncaught exceptions are hidden from the user. Advice: you should turn on exceptions wherever possible (they're standard practice in modern PHP) and turn off `display_errors` in production. And by the way, your favourite framework probably sets up an uncaught exception handler for you, to display a nice error page, send you an alert and whatnot. – BenMorel Dec 22 '19 at 15:24
  • 1
    @Benjamin correct, and I'm editing it. I mean you should never display that error message to the end user. – Michael Ryan Soileau Jan 24 '20 at 21:17