mysqli or die, does it have to die?

or is just an operator (very similar to ||).

The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.


Yes, you can provide a different function after the (or). I have tested the following:

mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));

function some_func($str) {
    die("ERROR: ".$str);
}

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 error message is one of the worst rudiments:

  • die throws the error message out, revealing some system internals to the potential attacker
  • such error message confuses casual users, because they don't understand what does it mean
  • Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
  • it kills the script irrecoverably. While exceptions can be caught and gracefully handled
  • die() gives you no hint of where the error has been 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.

Tags:

Mysql

Php

Mysqli