Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 771
chustar Avatar asked Jan 11 '09 06:01

chustar


People also ask

What does die () do in PHP?

The die() function prints a message and exits the current script.

What does die return in PHP?

It does not return. The script is terminated and nothing else is executed.

What is difference between exit and die in PHP?

The exit() method is only used to exit the process. The die() function is used to print the message. The exit() method exits the script or it may be used to print alternate messages. This method is from die() in Perl.

What does die function mean?

The die() is an inbuilt function in PHP. It is used to print message and exit from the current php script. It is equivalent to exit() function in PHP. Syntax : die($message)


2 Answers

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.

like image 184
nickf Avatar answered Oct 03 '22 06:10

nickf


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.

like image 39
Artelius Avatar answered Oct 03 '22 08:10

Artelius