php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #9482 || operator gives unexpected results
Submitted: 2001-02-27 10:52 UTC Modified: 2001-02-28 17:05 UTC
From: ssegarra at mitre dot org Assigned:
Status: Closed Package: *General Issues
PHP Version: 4.0.4pl1 OS: red hat 6.2
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: ssegarra at mitre dot org
New email:
PHP Version: OS:

 

 [2001-02-27 10:52 UTC] ssegarra at mitre dot org
<?

$db = mysql_connect("localhost", "web") || print "error connecting   ".mysql_error()." ".mysql_errno();
mysql_select_db("surveys");

$result = mysql_query("select * from attract") || print "error querying   ".mysql_error()." ".mysql_errno();
	
$i = 0;
while ($row = mysql_fetch_array($result)){ // && ($i++ < 5)){
	echo $row[0]." ".$row[1]."<br>";
}
?>

this script will repeatedly give me invalid MySQL Link Resource Warnings, but by changing the "||" to "or" it will work fine.

Thanks



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2001-02-28 17:05 UTC] torben@php.net
This isn't a bug; it's a result of the differing precedence for || and or (which
are otherwise identical, btw).

Try this: 

  $db = mysql_connect("localhost", "root") || print "error connecting";
  echo $db;

The output should be '1'. The reason is that || has higher precedence than =,
so PHP sees the above statement as:

  $db = (mysql_connect("localhost", "root") || print "error connecting");

...which means that $db is assigned the value of the expression in parens, which
in this case will always evaluate to 1, which is not a valid MySQL resource.

Next try this:

  ($db = mysql_connect("localhost", "web")) || print "error connecting ";
  echo $db;

The output should be 'Resource id #1', since the precedence has now been forced.
The other way to force precedence is to use the lower-precedence 'or', as you 
mentioned.

The operator precedence table can be found in the manual at:

  http://www.php.net/manual/en/language.operators.precedence.php


Hope this helps,

Torben

 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Feb 05 15:01:32 2025 UTC