$conn = mysql_connect($db_host,$db_user,$db_password) || die('Connection to mysql failed');
mysql_close($conn);
On executing this code, the following warning was displayed.
PHP Warning: mysql_close() expects parameter 1 to be resource, boolean given in script.php on line 45
$conn = mysql_connect($db_host,$db_user,$db_password) or die('Connection to mysql failed');
mysql_close($conn);
No Warning Now!?
And/or (sometimes written and or) is an English grammatical conjunction used to indicate that one or all). It is used as an inclusive or (as in logic and mathematics), because saying "or" in spoken language (or writing "or") might be inclusive or exclusive.
The difference between AND, OR is that AND evaluates both conditions must be true for the overall condition to be true. The OR evaluates one condition must be true for the overall condition to be true. In the OR result, if name is John then condition will be true. If any row has the age 22, then it will be true.
Conjunctions are used to groups of words, phrases and clauses together. The most common conjunctions are and, or and but.
We use words called conjunctions, like and, or, but, because and although, to join two parts of sentences.
&&
and ||
are logical operators -- they're for Boolean conditional statements. As @towr and @ChrisHayes point you can use and
and or
in place of the &&
and ||
syntax, albeit at a lower precedence than most other operators.
or
in this context, however, is completely different -- it's part of the control flow (see section 2.5.7: exit and return).
Boolean condition:
if ($foo == $bar || $bar != $bob)
Control flow:
mysql etc... or die();
You're receiving the error "PHP Warning: mysql_close() expects parameter 1 to be resource..." because you're not actually writing correct syntax, thus breaking your mysql_connect
statement.
and
and or
have higher lower precedence than &&
and ||
. To be more exact &&
and ||
have higher precedence than assignment operator ( =
) while and
and or
have lower.
http://www.php.net/manual/en/language.operators.precedence.php
Usually it doesn't make a difference, but there are cases when not knowing about this difference can cause some unexpected behaviour. See examples here:
http://php.net/manual/en/language.operators.logical.php
EDIT(suggested by @towr):
Applied to the question at hand, this means that in the first case we assign to $conn
the value mysql_connect(....) || die('....'),
because ||
has a higher precendence than =
. The problem here is that $conn
now is a boolean, and not a resource.
In the second case we OR
the expressions $conn = mysql_connect(....)
and die('....'),
because =
has a higher precendence than OR
. We do nothing with the boolean value, and $conn
is simply the resource we assigned to it in the first expression (if it didn't fail).
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