stack stack - 5 months ago 12
SQL Question

Fatal error: Call to a member function fetch() on boolean in {path}

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.

Answer

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.