How does "do something OR DIE()" work in PHP?

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.


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.


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.