$st = $this->db->prepare("SELECT * FROM invoices WHERE group_id=?");
$st->execute(array($id));
if($st->rowCount() >= 1){
foreach ($st as $row) {
$counter = $row["paymentAmount"];
$start = 1;
for($start; $start < $st->rowCount(); $start++) {
$counter = $counter + $row["paymentAmount"];
}
}
实际上会打印$row["paymentAmount"] + $row["paymentAmount"]
等等,具体取决于$row["paymentAmount"]
的数量$row["paymentAmount"]
。但问题是onlyOneEl e x = fromJust (lookup x counts) == 1
where gs = group (sort e)
counts = zip (map head gs) (map length gs)
的最后一个输出是2500。
有: 10000 10000 2500
结果是:7500 我希望它是:22500
如果最后的结果是3000,它应该是23000.所以我只需要这个代码从数据库中获取每一行,而不是最新的一行。
编辑:我希望它在SQL查询之外
答案 0 :(得分:2)
你不需要像这样的PHP逻辑。该功能内置于SQL中。
SELECT SUM(paymentAmount) FROM invoices WHERE group_id=?
答案 1 :(得分:0)
您应该让数据库处理总和,除非您有正当理由需要在PHP中处理它。使用此类操作可以提高数据库的效率,避免PHP中的循环。
SELECT SUM(paymentAmount) AS TotalPaymentAmount FROM invoices WHERE group_id = ?
然后,您可以将PHP更改为仅返回一行:
$row = $st->fetch();
echo $row["TotalPaymentAmount"];
如果您需要在SQL之外进行此计算,只需更改循环:
if($st->rowCount() >= 1){
//init the counter to 0 before you loop through your rows
$counter = 0;
//the foreach will iterate over your result set and add the paymentAmount to $counter.
foreach ($st as $row) {
$counter += $row["paymentAmount"];
}
//echo results outside of the loop
echo $counter;
}
答案 2 :(得分:0)
如果您需要故意编写外部SQL代码(例如,因为您需要对每一行进行进一步处理),那么我将按如下方式对其进行编码:
if ($st->rowCount() >= 1) {
$counter = 0;
foreach ($st as $row) {
$counter += $row["paymentAmount"];
}
}