我有一个基于PHP的购物车。除了最后一部分,一切都有效。单击更新数量时,它会更新购物车数量中的每个项目。我不知道为什么。这是按钮的代码:
修改
<?php
// start session
session_start();
// connect to database
//include 'config/db_connect.php';
include 'config/sa_db_connect.php';
// set page title
$page_title="Shopping Cart";
// include page header html
include 'layout_head.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
$name = isset($_GET['name']) ? htmlspecialchars($_GET['name']) : "";
if($action=='removed') {
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> was removed from your cart!";
echo "</div>";
}else if($action=='quantity_updated'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> quantity was updated!";
echo "</div>";
}
if(count($_SESSION['cart'])>0){
// remove all cart contents
echo "<div class='right-button-margin' style='overflow:hidden;'>";
echo "<a href='empty_cart.php' class='btn btn-default pull-right'>Empty Cart</a>";
echo "</div>";
// get the product ids
$ids = "";
foreach($_SESSION['cart'] as $id=>$value){
$ids = $ids . $id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
//start table
echo "<table class='table table-hover table-responsive table-bordered' style='margin:1em 0 0 0;'>";
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (GBP)</th>";
echo "<th style='width:15em;'>Quantity</th>";
echo "<th>Sub Total</th>";
echo "<th>Action</th>";
echo "</tr>";
$query = "SELECT idsale_Stock, model_no, sale_price FROM sale_Stock WHERE idsale_Stock IN ({$ids}) ORDER BY cat_description";
// $query = "SELECT id, name, price FROM products WHERE id IN ({$ids}) ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();
$total_price=0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$quantity=$_SESSION['cart'][$id]['quantity'];
$sub_total=$sale_price*$quantity;
echo "<tr>";
echo "<td>";
echo "<div class='product-id' style='display:none;'>{$id}</div>";
echo "<div class='product-name'>{$model_no}</div>";
echo "</td>";
echo "<td>£" . number_format($sale_price, 2, '.', ',') . "</td>";
echo "<td>";
echo "<form class='update-quantity-form'>";
echo "<div class='input-group'>";
echo "<input type='number' name='quantity' value='{$quantity}' min='1' class='form-control' required>";
echo "<span class='input-group-btn'>";
echo "<button type='submit' class='btn btn-default update-quantity'>Update</button>";
echo "</span>";
echo "</div>";
echo "</form>";
答案 0 :(得分:-2)
在update-quantity中提交按钮类型。所以当点击按钮时,页面正在重新加载。
删除type =&#34;提交&#34;来自更新数量。并尝试。
如果您在单击按钮时需要执行任何操作,则可以使用onclick。
或请使用event.preventdefault()来避免表单提交。
感谢。