繁体   English   中英

如何在SQL查询中添加发送数组并使用PHP计算SUM

[英]How to add send array in the SQL query and calculate SUM using PHP

我在变量$id = Array([0] => 5 , [1]=> 6)有一个数组。 现在,我想将值传递给SQL查询并计算SUM,但是不知何故,它不是在计算SUM,而是在显示输出100500,它应该是600(例如:100 + 500 = 600)。

我的PHP代码是:

$id = $_POST['id'];
for($i = 0; $i<count($id); $i++) {
$sql = getAmount($id[$i]);
}

function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
    $stmt->fetch();
echo $amount['total'];
 }

您不是对sql结果求和;

$id = $_POST['id'];
$sum = 0;
for($i = 0; $i<count($id); $i++) {
$sum = $sum + getAmount($id[$i]);
}
echo $sum;//Print the summing result

function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
    $stmt->fetch();
return $amount['total'];
 }

您应该从getAmount函数返回查询和结果,并且应该在循环中对返回的结果求和。 完成循环后,您可以打印总和结果。

amount必须为整数或浮点类型:int,bigint,tinyint,longint,float,double

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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