Php 从数组中查找值的和
我有一个购物车表,希望在状态为1的地方计算成本总和Php 从数组中查找值的和,php,mysql,sql,arrays,mysqli,Php,Mysql,Sql,Arrays,Mysqli,我有一个购物车表,希望在状态为1的地方计算成本总和 id cost status 1 10 1 2 10 1 2 10 1 2 10 2 我试过的代码是 $sql01 = "SELECT * FROM cart where status='1' "; $result01 = mysqli_query($con, $sql01); if (mysqli_num_rows($result01) > 0) { w
id cost status
1 10 1
2 10 1
2 10 1
2 10 2
我试过的代码是
$sql01 = "SELECT * FROM cart where status='1' ";
$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0)
{
while($row = mysqli_fetch_assoc($result01))
{
$price = array_sum($row);
echo "sum of cod:"; echo $price;
echo "<br>";
}
}
结果应该是
30
使用以下命令:
SELECT sum(cost) FROM cart group by status having status='1'
您正在计算每行的总和。相反,您应该尝试以下方法:
$sql01 = "SELECT * FROM cart where status='1'";
$result01 = mysqli_query($con, $sql01);
$cost_array = array();
if (mysqli_num_rows($result01) > 0)
{
while($row = mysqli_fetch_assoc($result01))
$cost_array[] = $row['cost'];
}
echo "Result: ".array_sum($cost_array);
或者(更好!)通过以下方式优化MySQL查询:
SELECT sum(cost) finalprice FROM cart where status='1' GROUP BY status
现在,您可以使用
$row['finalprice']
访问您的总和。这是您的查询:
SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status
PHP代码:
$sql01 = 'SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status'
$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0)
{
while($row = mysqli_fetch_assoc($result01))
{
echo 'sum of cod:' . $row['price'] . '<br>';
}
}
$sql01='从购物车中选择金额(成本)作为价格,其中状态为='1'按状态分组'
$result01=mysqli_查询($con,$sql01);
如果(mysqli_num_行($result01)>0)
{
而($row=mysqli\u fetch\u assoc($result01))
{
回显“cod之和:”.$row[“价格”]。
;
}
}
在中阅读有关分组方式的更多信息:
一种方法是用SQL计算总和,如其他答案所示。如果要在PHP中执行此操作,可以将
cost
列添加到变量中:
$total_cost = 0;
while ($row = mysqli_fetch_assoc($result01)) {
$total_cost += $row['cost'];
}
echo "Result: $total_cost";
它比您的代码更简单:在SQL中,您应该使用
"Select sum(cost) from cart where status = '1';"
您正在对行中的所有数字求和,而不是将所有成本相加。它不应该每次都打印
10
。第一行应该打印12:1+10+1
@AdrianCidAlmaguer,而不是只返回一行,就像这里一样!
"Select sum(cost) from cart where status = '1';"