简体   繁体   中英

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

I've been searching for the better part of five days (no joke, don't want to bother you guys for nothing), but I can't seem to be getting this right. I want to display the total amount of a column (tech) on the screen using a function in PHP. Don't worry, the $day part works in other functions. I don't think it is part of the problem. Thank you in advance.

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

}

My database table looks like this:

在此处输入图片说明

You need to make the SUM() the column in the query :

function 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' should be enclosed by single quotes .

FOR SUM of column name query should be like this

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

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