我的购物车永远不会回显为空,即使该值为0。 我错过了什么?请指出我正确的方向。 我试图移动else语句,但只会导致页面错误。
<?php
session_start();
include "cart.php";
include "style.php";
if (isset($_GET['add'])) {
$_SESSION['id'.$_GET['add']]++;
}
if (isset($_GET['empty'])) {
$_SESSION['id_'.$_GET['empty']]--;
session_unset();
}
function cart() {
echo "<h3>Shopping cart!</h3>";
echo "<table>
<tr>
<td>Product</td>
<td>Quantity</td>
<td>Price</td>
<td><a href='shoppingcart.php?empty=$name'>[Empty]</a></td>
</tr>";
foreach($_SESSION as $name => $value) {
if ($value > 0) {
echo "<table><tr><td>$name</td><td>$value</td></tr></table>";
}
else {
echo "Cart is empty";
}
}
}
?>
答案 0 :(得分:0)
会话不是购物车,购物车不是会话。购物车应该基本上是一个包含数组的会话属性。
这是基本想法(从您的代码开始):
<?php
session_start();
//create default empty cart
$cart = array();
if(isset($_SESSION['cart']))
{
//get the cart from the session
$cart = $_SESSION['cart'];
}
if (isset($_GET['add']))
{
$cart[] = $_GET['add']; //add to cart array
}
if (isset($_GET['empty']))
{
$cart = array(); //set cart array to empty array
}
//put the cart in the session
$_SESSION['cart'] = $cart;
function cart()
{
?>
<h3>Shopping cart!</h3>
<table>
<tr>
<td>Product</td>
<td>Quantity</td>
<td>Price</td>
<td><a href='shoppingcart.php?empty=true'>[Empty]</a></td>
</tr>
<?php
if(empty($cart))
{
echo "Cart is empty";
}
else
{
echo "<table>";
foreach($cart as $name => $value)
{
echo "<tr><td>$name</td><td>$value</td></tr>";
}
echo "</table>";
}
}