在循环中循环并添加数字

时间:2016-11-29 16:36:43

标签: php mysql while-loop

我从数据库中获取数据并根据billing_type和date执行计算。我能够循环并正确执行每个日期的计算。但是,我现在正在尝试将计算结果加起来。

例如,如果计算结果相等: 10, 7, 30, 28

我希望能够添加它们并显示75

的结果

这是我的代码:

$sql = "SELECT billing_amount, billed_by, open, SUM(tickets), COUNT(casekey)
        FROM pcnclientreport
        WHERE open = '$date' GROUP BY '$date'";

$res = mysqli_query($conn, $sql);

while($row = mysqli_fetch_assoc($res) ){
    if($row['billed_by'] == 'Month'){ 
        $gsliability = $row['billing_amount'];
    }
    else if ($row['billed_by'] == 'Case'){
        $gsliability = ($row['billing_amount'] * $row['COUNT(casekey)']);
    }
    else if ($row['billed_by'] == 'Ticket'){
        $gsliability = ($row['billing_amount'] * $row['SUM(tickets)']);
    }
}

echo $gsliability

1 个答案:

答案 0 :(得分:1)

$sql = "SELECT billing_amount, billed_by, open, SUM(tickets), COUNT(casekey)
    FROM pcnclientreport
    WHERE open = '$date' GROUP BY '$date'";

$res = mysqli_query($conn, $sql);

$sum = 0;
while($row = mysqli_fetch_assoc($res) ){

    $gsliability = 0;

    if($row['billed_by'] == 'Month'){ 
        $gsliability = $row['billing_amount'];
    }
    else if ($row['billed_by'] == 'Case'){
        $gsliability = ($row['billing_amount'] * $row['COUNT(casekey)']);
    }
    else if ($row['billed_by'] == 'Ticket'){
        $gsliability = ($row['billing_amount'] * $row['SUM(tickets)']);
    }

    $sum += $gsliability;
}

echo $sum;