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

chustar picture chustar · Jan 11, 2009 · Viewed 93.7k times · Source

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.

Answer

nickf picture nickf · Jan 11, 2009

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.