views:

7891

answers:

4

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.

+19  A: 

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.

nickf
Thanks for the help, mate.
chustar
Niiiice and so simple. I finally understand how it works. Could have realised this myself, d'oh!
Peter Perháč
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
+7  A: 

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
+7  A: 

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
A: 

$con=mysql_connect($host, $user, $pass) if(!$con) { die("could not connect"); } else { echo "Connected"; }


By Arun Kumar Mishra

Arun Kumar