Jump to content

Recommended Posts

Hello, I know this makes me seem stupid, but I have been coding in PHP for about two years, and always had this question.

For the longest time when doing the mysql_query() call I would never use the die condition to check for failure because I thought it didnt work when returning a result set.

I.E.  $result = mysql_query($sql) || die();

Then one day I tried replaced the || with the words OR and it works. It seems the || doesnt allow the result variable to get filled but the OR allows it. Is it me, or does this baffle anybody else?
Link to comment
https://forums.phpfreaks.com/topic/22827-whats-the-deal-with-mysql_query-or-or/
Share on other sites

Seems the cause is related to operator presedence.

Here try doing a query like:

$sql = "SELECT first_name FROM test";
$result = mysql_query($sql) || die("Failure!");
//$result is not defined here, even though the query is valid.

$sql = "SELECT first_name FROM test";
$result = mysql_query($sql) OR die("Failure!");
//$result IS defined here

from a comment in the operators precedence section of [url=http://us2.php.net/manual/en/language.operators.php#language.operators.precedence]the manual[/url]:

[quote]
<?php $a = $b && $c; ?>
<?php $a = $b AND $c; ?>

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN - after that - compare the success of this with the value of $c
[/quote]
'||' is a boolean operator, and it always results in either true or false. So in your example above, $result would become TRUE instead of being a query result (as long as the query was valid, in which case die() would be called). The 'OR' operator always returns the value of the first operand, and it will evaluate operands until it either finds one that can resolve to TRUE, or it runs out of operands. Sound confusing? It is. Maybe this example will help:

$result = "0" || 0 || false || "hello"; // $result becomes TRUE
$result = "0" OR 0 OR false OR "hello" ; $result becomes "0"

Just don't use '||' to do what you're trying to do.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.