问题
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