[英]Adding sums in php for each
$connect = mysqli_connect("localhost", "root", "", "hempbag_db") or die("Connection failed");
foreach($a as $b){
foreach($b as $c){
$query5 = "SELECT P_price tbl_products WHERE PID='".$c['PID']."' ";
$get_price = mysqli_query($connect, $query5);
$get_price1 = mysqli_fetch_assoc($get_price);
$price = ($get_price1['P_price'])+ $price + 0; // This does not add
}
}
$price
does not add only takes the last value of the data inside the loop. $price
不会仅添加循环内数据的最后一个值。
How can I add them? 如何添加它们?
I also used: 我还用过:
$price = ($get_price1['P_price'])+0;
$new_price += $price;
Still failed. 仍然失败。
Thank You! 谢谢!
Try this: $total_price
is sum of price. 试试这个:
$total_price
是价格的总和。
$connect = mysqli_connect("localhost", "root", "", "hempbag_db") or die("Connection failed");
$total_price = 0;
foreach($b as $c) {
$query5 = "select P_price from tbl_products where PID='".$c['PID']."' ";
$get_price = mysqli_query($connect, $query5);
$get_price1 = mysqli_fetch_assoc($get_price);
$total_price += $get_price1['P_price'];
}
echo $total_price;
initialise $price
before looping through the array. 在遍历数组之前初始化
$price
。
$connect = mysqli_connect("localhost", "root", "", "hempbag_db") or die("Connection failed");
$price = 0;
foreach($b as $c)
{
$query5 = "select P_price from tbl_products where PID='".$c['PID']."' ";
$get_price = mysqli_query($connect, $query5);
$get_price1 = mysqli_fetch_assoc($get_price);
$price = ($get_price1['P_price'])+$price;
// other way (highly recommended)
$price += ($get_price1['P_price']);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.