我在会话方面存在购物车问题 - 这些代码有效,但会话中存在语义错误,我无法弄清楚。
每次我将一个项目添加到购物车而不是将新项目添加到购物车或不添加它会覆盖它。我打算将它附加在一个页面上,该页面显示购物车中所有添加的项目及其总数。
非常感谢任何帮助,谢谢。 :)
这是我的购物车代码页:
<?php
$serverName = "example.com";
$dbName = "abc1234";
$user = "abc2345";
$pass = "bbc334";
$con = mysqli_connect($serverName, $user, $pass, $dbName);
if(!$con){
die("failure to connect to the server ".mysqli_connect_error());
}
?>
<?php session_start();
if (isset($_GET['action']) && $_GET['action'] == "add")
{
$product = intval($_GET['id']);
if(isset($_SESSION['cart'][$product])){
$_SESSION['cart'][$product]['quantity']++;
} else {
$accessdata = "SELECT * FROM Software WHERE id = ($product)";
$newquery = mysqli_query($con, $accessdata);
if(mysqli_num_rows($newquery)!= 0){
$row2 = mysqli_fetch_array($newquery);
$_SESSION['cart'][$row2['id']] = array("quantity" => 1, "cost" => $row2['price']);
}else{
$mes = "Invalid ID";
}
}
} error_reporting(0);
?>
<h2 class="inform"><?php if(isset($mes)){echo $mes;}?></h2>
<?php
//counter quantity
if(isset($_POST['submit'])){
foreach($_POST as $access => $value){
$access = explode("-", $access);
$access = end($access);
$access = explode("submit", $access);
$access = end($access);
if($_POST['quantity-'.$access] <= 0){
unset($_SESSION['cart'][$access]);
} else if($_POST['quantity-'.$access] >=50){
$_SESSION['cart'][$access]['quantity'] = 50;
}else{
$_SESSION['cart'][$access]['quantity']= $value;
}
}
}
?>
<h1> View Shopping Cart </h1>
<?php
$dataaccess = "SELECT * FROM Software WHERE id IN (";
foreach($_SESSION['cart'] as $product => $value){
$dataaccess .= $product. ",";
}
$dataaccess = substr($dataaccess, 0, -1).") ORDER BY name ASC";
$query = mysqli_query($con, $dataaccess);
if(empty($query)){
echo "<br /> Add an item to the cart to proceed ";
}
?>
<form method="POST" action="shoppingcart.php">
<fieldset>
<table>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Cost</th>
<th>Total Price</th>
</tr>
<?php
$dataaccess = "SELECT * FROM Software WHERE id IN (";
foreach($_SESSION['cart'] as $product => $value){
$dataaccess .= $product. ".";
}
$dataaccess = substr($dataaccess, 0, -1). ") ORDER BY name ASC";
$query = mysqli_query($con, $dataaccess);
$totalcost = 0;
if(!empty($query)){
while($row = mysqli_fetch_array($query)){
$subtotal = $_SESSION['cart'][$row['id']] ['quantity'] * $row['price'];
$totalcost += $subtotal;
?>
<tr>
<td><?php echo $row['name']; ?> </td>
<td><input type="text" name="quantity-<?php echo $row['id']; ?>" size="5" value="<?php echo $_SESSION['cart'][$row['id']]['quantity']; ?>" /></td>
<td><?php echo "£".$row['price'];?></td>
<td><?php echo "£".$_SESSION['cart'][$row['id']] ['quantity']*$row['price'];?></td>
</tr>
<?php
}
}
?>
<tr>
<td></td>
<td></td>
<td>TOTAL: </td>
<td><?php echo "£".$totalcost;?></td>
</tr>
</table>
<input type="submit" name="submit" value="Update Cart" /></fieldset>
</form>
<p>To remove an item, set quantity to 0</p>
</div>