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.
The die() function prints a message and exits the current script.
It does not return. The script is terminated and nothing else is executed.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With