我创建一个简单的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>
答案 0 :(得分:0)
替换代码的这一部分
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
中的值将有总金额。