Page 1 of 1

PHP / Cake Bug

Posted: Mon Aug 31, 2009 11:31 am
by John Cartwright
PHP Version 5.2.1
Cake version Revision: 2573

Came across a relatively old code base yesterday because one of our sites suddenly weren't down without reason. The site was still functional and not under any high load, and it was apparent it was the CakePHP software at fault. Basically, the database connection was made, but any queries (which I knew should yield results) returned an empty array. It took me quite awhile to figure out what exactly was going on, but it came down to this method (in the mysql dbo file).

Code: Select all

/**
 * Executes given SQL statement.
 *
 * @param string $sql SQL statement
 * @return resource Result resource identifier
 * @access protected
 */
    function _execute ($sql)
    {
        return mysql_query($sql, $this->connection) or die(mysql_error());
    }
Everything looks fine and dandy, when I was debugging I noticed this method was returning true/false, which at first glance is ok because non SELECT sql will return a boolean of it's success. However, on a SELECT statement, it will still returning true! I adding a var_dump() inside the method and it would dump a resource (what we would expect). It seemed the resource was being returned as a boolean in all cases for some reason.

So to fix the bug, I had to assign the result of mysql_query() and return it's return seperately.

Code: Select all

 
    function _execute ($sql)
    {
        $result = mysql_query($sql, $this->connection) or die(mysql_error());
        return $result;
    }
Any ideas what the heck is happening here?

Re: PHP / Cake Bug

Posted: Mon Aug 31, 2009 2:19 pm
by Darhazer
or is my "favorite" operator. IMO it, as well as and should be removed from PHP

or is a boolean operator.
However it have a lower precedence that an assigment
so

Code: Select all

$result = true or false;
comes to:

Code: Select all

$result = true;
$result or false; // it's boolean expression, which result is not assigned and just discarded.
But when you return the value, this is what's happening:

Code: Select all

return ($result or false); // which produces a boolean result
Hope this makes sense. I posted detailed explanation in my blog, but it's in Bulgarian :wink:
Darhazer's ego wrote:Great post :!:

Re: PHP / Cake Bug

Posted: Mon Aug 31, 2009 5:05 pm
by John Cartwright
Thanks a bunch for the explanation. Was scratching my head over this one for a few hours :)