-1

Here is my code:

$money = $db_con
->prepare(" SELECT SUM(asker_amount) asker, SUM(responder_amount) responder
            FROM money WHERE post_id = ? AND author_id = ? AND paid IS NULL")
->execute(array($ques_id, $author_ques_id))
->fetch(PDO::FETCH_ASSOC);
$asker_amount = $money['asker'];
$responder_amount = $money['responder'];

It doesn't execute and throws this error:

Fatal error: Call to a member function fetch() on boolean in {file path} on line 5 (->fetch( ...)

Ok what's wrong? And how can I fix it?

Note: That query works as well, I've tested it in phpmyadmin.

stack
  • 10,280
  • 19
  • 65
  • 117
  • 1
    The `execute` function returns a boolean: http://php.net/manual/en/pdostatement.execute.php – Peter Gordon Jun 16 '16 at 14:23
  • @pgmann Do you mean I have to fetch `$money` instead of chaining it to `execute()` ? – stack Jun 16 '16 at 14:24
  • 2
    Obviously it DOESN'T work well here, as some stage of that process is failing and returning a boolean false. In general, never EVER chain DB calls like that. It assume nothing will ever fail, which is exactly the wrong attitude. Queries can fail even if the sql syntax is 100% perfect. **ALWAYS** assume failure, check for failure (at every stage), and treat success as a pleasant surprise. – Marc B Jun 16 '16 at 14:24
  • Possible duplicate of [Call to a member function on a non-object](http://stackoverflow.com/questions/54566/call-to-a-member-function-on-a-non-object) – Henders Jun 16 '16 at 14:39

1 Answers1

3

Try this instead.

$query = $db_con->prepare(" SELECT SUM(asker_amount) asker, SUM(responder_amount) responder
        FROM money WHERE post_id = ? AND author_id = ? AND paid IS NULL");
$query->execute(array($ques_id, $author_ques_id));
$money = $query->fetch(PDO::FETCH_ASSOC);
$asker_amount = $money['asker'];
$responder_amount = $money['responder'];

You should be assigning $money the result of the final fetch only.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Peter Gordon
  • 1,075
  • 1
  • 18
  • 38