111

I'm writing a php app to access a MySQL database, and on a tutorial, it says something of the form

mysql_connect($host, $user, $pass) or die("could not connect");

How does PHP know that the function failed so that it runs the die part? I guess I'm asking how the "or" part of it works. I don't think I've seen it before.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
chustar
  • 12,225
  • 24
  • 81
  • 119

4 Answers4

144

If the first statement returns true, then the entire statement must be true therefore the second part is never executed.

For example:

$x = 5;
true or $x++;
echo $x;  // 5

false or $x++;
echo $x; // 6

Therefore, if your query is unsuccessful, it will evaluate the die() statement and end the script.

Community
  • 1
  • 1
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 1
    Good explanation. This "implied if" language construct of PHP is a little dangerous, because you can have statements that you think get executed but really don't, and that's not as obvious as if you had an if block. – Petruza Aug 07 '09 at 15:34
  • 7
    This is called short-circuit evaluation and is useful in languages other than PHP as well. – Mr Griever Feb 08 '11 at 23:25
  • 1
    By the way, you can only use a single statement after OR. A block statement will fail syntax checking (e.g. actual error message could be Parse error: syntax error, unexpected '{' in ...) – Scott Chu May 21 '12 at 17:26
  • And here I was, thinking this was some kind of advanced feature like python's `with` statement, when it's actually just a boolean expression... I think extra care should be taken when using this expression if you're expected to perform a cleanup in case of errors. Please, correct me if I'm wrong, but if you do `func_call($file) or die();` and the function fails, then the file is left open when the scripts dies. – pedromanoel Nov 27 '12 at 11:06
  • @Petruza Is it even good practice to use `or` in situations where an `if` could work? – limeandcoconut Feb 05 '15 at 03:48
  • @BrassApparatus Now, looking at my comment 5 years later, I would say the _or shortcut_ is not so bad after all, it's simple, concise and elegant. But the danger of taking for granted than rightmost expressions will get evaluated when they might not still holds. (I would say a good practice is never using as an expression something that produces a side effect, like _++_) In every situation that an _or shortcut_ works, a classic _if_ would work too. What I would advise against every time is using _die()_, one should handle error conditions gracefully. – Petruza Feb 09 '15 at 23:12
  • Similarly works `AND` operator, but in this case second operator will never executed if the first returns `FALSE` – Dmitry Apr 07 '17 at 12:03
39

PHP's or works like C's || (which incidentally is also supported by PHP - or just looks nicer and has different operator precedence - see this page).

It's known as a short-circuit operator because it will skip any evaluations once it has enough information to decide the final value.

In your example, if mysql_connect() returns TRUE, then PHP already knows that the whole statement will evaluate to TRUE no matter what die() evalutes to, and hence die() isn't evaluated.

If mysql_connect() returns FALSE, PHP doesn't know whether the whole statement will evaluate to TRUE or FALSE so it goes on and tries to evalute die() - ending the script in the process.

It's just a nice trick that takes advantage of the way or works.

Artelius
  • 48,337
  • 13
  • 89
  • 105
  • +1 for naming short circuiting. Might also have named "side effect". We are not interested at all in the die() return code, we just want the effect of its execution. (It is not always going to be die()). This is not always popular with the purists as some effects can be obscure. – mckenzm Sep 05 '16 at 04:39
  • and this isnt all. you can also use and to combine stuff, where you want that one thing definitely works before doing a second thing. – My1 Jan 17 '18 at 14:36
14

It works as others have described.

In PHP, do not use "die", as it does NOT raise an exception (as it does in Perl). Instead throw an exception properly in the normal way.

die cannot be caught in PHP, and does not log - instead it prints the message ungracefully and immediately quits the script without telling anybody anything or giving you any opportunity to record the event, retry etc.

MarkR
  • 62,604
  • 14
  • 116
  • 151
1

If you would like to add more code if the connection doesn't work, beyond a die statement:

$con=mysql_connect($host, $user, $pass)
if(!$con)
{
     // ... add extra error handling code here
     die("could not connect");
}
else
{
     echo "Connected";
}
Matthew Lock
  • 13,144
  • 12
  • 92
  • 130
Arun Kumar
  • 57
  • 1