PDO count row values based on WHERE

≯℡__Kan透↙ 提交于 2020-02-06 09:07:21

问题


I looked over PHPDelusions website few times before asking this, as well as used Google but I still can't seem to get the code to work, or find a solution that remotely mirrors my question in general.

I made a super simple PHP7 script for managing Receipts. The fields are simple.

id (int 12), amount (varchar 8), category (int 2), date (date)

The problem I'm facing is I'm trying to Count the Total Amount of money based on Categories. So let's say Category = 1 would count all Amounts with that respective category and so on.

Here is my existing code.

function getAmountCount(PDO $pdo, $cat) {

    $data = $pdo->prepare("SELECT COUNT(*) FROM `receipts` WHERE category = :cat_id");
    $data->bindValue(':cat_id', $cat, PDO::PARAM_INT);
    $data->execute();
    $result = $data->fetchColumn();

    echo money_format('%(#10n', $result['amount']).' CAD';

}

#and here is how we call it in the script
echo getAmountCount($pdo, 1);

The current code returns: $ 0.00 CAD


回答1:


You have a couple of issues. Firstly, to get the total amount of money for each category, you should be using SUM, not COUNT. COUNT will simply return a count of the number of rows associated with that category. Secondly, fetchColumn returns a single value, not an array. Change your query to this:

SELECT SUM(amount) AS amount FROM `receipts` WHERE category = :cat_id

and

echo money_format('%(#10n', $result['amount']).' CAD';

to

echo money_format('%(#10n', $result).' CAD';


来源:https://stackoverflow.com/questions/54067256/pdo-count-row-values-based-on-where

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!