简体   繁体   中英

How to sum the total value

I am trying to sum up the value. I have stored in the database price and qty. The total = price * qty for that particular item.

I would like to sum all of the items for a sub total.

$sql = "SELECT * FROM parts WHERE jobno = '$id'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $results['entrants'][] = array(
            'partno'          => $row['partno'],
            'description'        => $row['description'],
            'price' => $row['price'],
            'qty'          => $row['qty'],
            'total' => $row['price'] * $row['qty'],
        );
    }
} else {
    // Create an empty placeholder record if no entrants were found
    $results['entrants'][] = array(
        'partno'          => NULL,
        'description'        => NULL,
        'price' => NULL,
        'qty'          => NULL,
        'total' => NULL,
    );
}

I only know SELECT sum - which I don't think will work because I am not getting the information from the database but from the above.

Just keep track as you go:

$subTotal = 0;
while ($row = $result->fetch_assoc()) {
    $lineTotal = $row['price'] * $row['qty'];
    $subTotal += $lineTotal;
    $results['entrants'][] = array(
        //...
        'total' => $lineTotal;
    );
 }
$results['subtotal'] = $subTotal;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM