当我在我的网页上调用此功能时,它应该反映出购物车中产品的总价值,但它只是回显了产品ID最高的产品的价值。而不是这些值的总和加起来。
function total_price() {
$total = 0;
global $link;
$ip = getIp();
$sel_price= "select * from cart where ip_add='$ip'";
$run_price= mysqli_query($link, $sel_price);
while($p_price=mysqli_fetch_array($run_price)) {
$pro_id = $p_price['id'];
$pro_price = "select * from products where id='$pro_id'";
$run_pro_price = mysqli_query($link, $pro_price);
while ($pp_price = mysqli_fetch_array($run_pro_price)){
$product_price = array($pp_price['prijs']);
$values = array_sum($product_price);
$total = number_format((float)$values, 2, ',', '');
}
}
echo "€ " .$total;
}
答案 0 :(得分:1)
没有理由使用array_sum
。具有一个元素的数组的总和就是该元素的值。如果您将每个价格推到数组上,然后在循环结束时计算总和,则可以使用array_sum
。但是你可以通过循环每次添加总值,所以没有必要这样做。
while ($pp_price = mysqli_fetch_array($run_pro_price)){
$values += $pp_price['prijs'];
}
}
$total = number_format((float)$values, 2, ',', '');
echo "€" . $total;
您也可以在一个查询中执行所有操作:
$sel_total = "SELECT SUM(prijs) AS total
FROM cart
JOIN products ON cart.id = product.id
WHERE ip_add = '$ip'";
$res = mysqli_query($sel_total);
$row = mysqli_fetch_assoc($res);
$total = number_format($row['total'], 2, ',', '');
echo "€" . $total;
答案 1 :(得分:0)
$total += number_format((float)$values, 2, ',', '');
应该有效
答案 2 :(得分:0)
<?php
function total_price() {
$values = 0;
$total = 0;
global $link;
$ip = getIp();
$sel_price= "select * from cart where ip_add='$ip'";
$run_price= mysqli_query($link, $sel_price);
while($p_price=mysqli_fetch_array($run_price)) {
$pro_id = $p_price['id'];
$pro_price = "select * from products where id='$pro_id'";
$run_pro_price = mysqli_query($link, $pro_price);
while ($pp_price = mysqli_fetch_array($run_pro_price)){
//$product_price = array($pp_price['prijs']);
//this will cumulate sum
$values += $pp_price['prijs'];
//$total = number_format((float)$values, 2, ',', '');
}
}
//this will format result
$total = number_format((float)$values, 2, ',', '');
echo "€ " .$total;
}
btw为什么不尝试使用JOIN语句???