"mysqli or die, does it have to die?" Code Answer


does it have to die

quite contrary, it shouldn't or die() ever.
php is a language of bad heredity. very bad heredity. and or die() with an error message being one of the worst rudiments:

  • die throws an error message out, revealing some system internals to a potential attacker
  • it is confusing innocent users with strange messages and leaving them no interface to work with, so they'd likely just drop out.
  • it kills the script in the middle, so it may cause torn design (or no design at all) shown (i.e. an incomplete render of the page the user requested)
  • killing the script irrecoverably. while thrown exception can be caught and gracefully handled
  • die() gives you no hint of the place where the error occurred. and in a relatively big application it will be quite a pain to find.

so, never use die() with mysql errors, even for the temporary debugging: there are better ways.

instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code

mysqli_report(mysqli_report_error | mysqli_report_strict);

and after that just write every mysqli command as is, without any or die or anything else:

$result = mysqli_query($link, $sql);

this code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.

a more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on php error reporting.

By Gilko on March 23 2022

Answers related to “mysqli or die, does it have to die?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.