簡體   English   中英

如何使用MySQL和PHP獲取列中的總和

[英]How to get the sum in a column using MySQL and PHP

我一直在尋找五天的大部分時間(不要開玩笑,不想無所事事地打擾你們),但是我似乎無法做到這一點。 我想使用PHP中的函數在屏幕上顯示一列(技術)的總量。 不用擔心,$ day部分可以在其他功能中使用。 我認為這不是問題的一部分。 先感謝您。

function calc_tech($day){

    include("connect.php"); // include database connection

    $res = $mysqli -> query(" SELECT * FROM sales WHERE day = $day ") or die($mysqli->error); // Fetch data from the table

    while($val = $res -> fetch_array()){
        $tech_total = $val[tech] += $val[tech];
    }

    echo $tech_total; // Echo the result
    //echo "42";

    $res -> free(); // Free the query results
    $mysqli -> close(); // Close mysqli object

}

我的數據庫表如下所示:

在此處輸入圖片說明

您需要將SUM()設置為查詢中的列:

函數calc_tech($ day){

include("connect.php"); // include database connection

$res = $mysqli -> query(" SELECT  SUM(tech) as sum FROM sales WHERE day = $day ") or die($mysqli->error); // Fetch data from the table

$val = $res -> fetch_array();
    $tech_total = $val['sum'];


echo $tech_total; // Echo the result

}

1) '$day'應該用單引號引起來。

SUM of column name查詢的FOR SUM of column name應該是這樣的

"select sum(tech) as Toatal from sales where day='$day';"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM