循环使用mysql的结果和sum值


Loop through results from mysql, and sum values

我使用while循环来处理这样的表记录:

$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
    while ($show_s = mysqli_fetch_assoc($result)) {
        $quantity = $show_s['sells_quantity'];
    } 
    mysqli_free_result($result); 
}

我有我所有的表格记录,现在我想总结所有的数量字段,但我不知道怎么做。

例如,如果我为2, 1, 5, 1, 3, 6等记录获得了10个记录数量,我想将它们相加如下:2+1+5+1+3+6 = 18

如果你能在mysql中做一些事情,就去做吧。使用SUM聚合函数:

$get_s = "SELECT SUM(sells_quantity) as sells_sum FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
    $show_s = mysqli_fetch_assoc($result);
    echo $show_s['sells_sum'];
} 
mysqli_free_result($result);

尽管如此,如果您需要某些行的值,您可以在循环中计算总和:

$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
    $total = 0;
    while ($show_s = mysqli_fetch_assoc($result)) {
        $quantity = $show_s['sells_quantity'];
        $total += $quantity; 
    } 
    mysqli_free_result($result); 
    echo $total;
}

但mysql SUM()更可取。