num_rows()的奇怪行为

EDIT

For heaven's sake, this is not a duplicate. Do not close it as such. I'm not inquiring about what the error means. I'm more interested in knowing why this is giving me an error in this case while it works fine when used at other places.

For a query such as:

$this->db->select('user_id');
$this->db->from("members");
$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)));
$query = $this->db->get();  
if($query->num_rows() == 1)
{
   // some logic goes here
}

I'm getting the following error.

Call to a member function num_rows() on boolean

If I use $this->db->last_query(), I'm getting the following result:

SELECT `user_id`
FROM `members`
WHERE `username` = 'adg'
AND `password` = '3a1c21a559ed42d6ce17c0b8205b6bda2465c2a8'

The query is 100% correct and when run in MySql console, returns an empty set (0 rows) which is fine. But why then is it returning boolean when used in the code.

By the way, I'm using num_rows() on the $query object in various other places and that seem to be working fine.

CI version is 3.1.3

Update

  • var_dump($query) is printing out bool(false)

It's not well documented but when a query fails a boolean might be returned instead of a CI_DB_result object. That is what is happening to you. My first guess as to why it happens in your example is that some piece of data is being improperly escaped - most likely in the where statement. Try this.

$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)), NULL, FALSE);

And see if that helps.

I have, on occasion, when queries are complicated, had to resort to the following check on my results like this.

if($query instanceof CI_DB_result && $query->num_rows() == 1) {...

just to make sure I'm not trying to "Call to a member function num_rows() on boolean"