gpt4 book ai didi

php - 用php计算元素的总价

转载 作者:行者123 更新时间:2023-11-30 22:15:57 24 4
gpt4 key购买 nike

我创建了一个简单的 php 购物车:

  • 添加产品数量。
  • 更新产品数量。

我想计算购物车中所有商品的总价,但我不知道如何计算?

我用这段代码显示项目:

<?php
session_start();
$where = implode(",",$_SESSION['product']);
$get_p = $mysqli->prepare("select id,name,price,imgs,quantity from products where id IN ($where)");
$get_p->execute();
$get_p->bind_result($id,$name,$price,$imgs,$quantity);
$get_p->store_result();
while($get_p->fetch()) {
$qty = $_SESSION["qty"][$id];
$total = $qty * $price;
?>
<tr>
<td><img src="<?php echo htmlspecialchars($imgs); ?>"/></td>
<td><?php echo htmlspecialchars($name); ?></td>
<td><?php echo htmlspecialchars($price)."×".$qty; ?></td>
<td><input type="number" value="<?php echo $qty; ?>" min="1" name="qty_cart"></td>
<td><input type="submit" value="delete" name="delete<?php echo $id; ?>"/></td>
<?php
if(isset($_POST["delete".$id])) {
unset($_SESSION['product'][$id]);
}
?>
</tr>
<?php
}

?>
</table>
<div class="price_all_items">
</div>
<input type="submit" name="sub" value=""/>
</form>

最佳答案

替换这部分代码

while($get_p->fetch()) {
$qty = $_SESSION["qty"][$id];
$total = $qty * $price;

有了这个

$totalSum = 0;
while($get_p->fetch()) {
$qty = $_SESSION["qty"][$id];
$total = $qty * $price;
$totalSum += $total;

在循环结束后,$total 中的值将是总金额。

关于php - 用php计算元素的总价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38286918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com