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

PhpMysqlException HandlingConditional

Php Problem Overview


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.

Php Solutions


Solution 1 - 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.

Solution 2 - Php

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.

Solution 3 - Php

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.

Solution 4 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchustarView Question on Stackoverflow
Solution 1 - PhpnickfView Answer on Stackoverflow
Solution 2 - PhpArteliusView Answer on Stackoverflow
Solution 3 - PhpMarkRView Answer on Stackoverflow
Solution 4 - PhpArun KumarView Answer on Stackoverflow