我正在尝试做一个购物车项目。我认为基于我为产品列表中的项目设置表单的方式,只有已选择的项目会显示在购物车中,而是显示所有三个项目,无论我点击哪一个。有人能告诉我需要改变什么。
列出产品的主页:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Final Project</title>
</head>
<body>
<?php
$_SESSION['maxItems'] = 2;
?>
<form id="item01" method="post" action="cart.php">
<?php $_SESSION['cart'][0] = array('name'=>'item01','price'=>'$11'); ?>
<label>Item 01 for sale</label>
<input type="submit" value="Add to cart" name="item01">
</form>
<br>
<form id="item02" method="post" action="cart.php">
<?php $_SESSION['cart'][1] = array('name'=>'item02','price'=>'$22'); ?>
<label>Item 02 for sale</label>
<input type="submit" value="Add to cart" name="item02">
</form>
<br>
<form id="item03" method="post" action="cart.php">
<?php $_SESSION['cart'][2] = array('name'=>'item03','price'=>'$33'); ?>
<label>Item 03 for sale</label>
<input type="submit" value="Add to cart" name="item03">
</form>
</body>
</html>
我购物车页面的php代码:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$max_items = $_SESSION['maxItems'];
for($i=0; $i <= $max_items; $i++){
$current_name = $_SESSION['cart'][$i]['name'];
$current_price = $_SESSION['cart'][$i]['price'];
echo "item is " . $current_name . " " . $current_price . "<br>";
}
?>
</body>
</html>
答案 0 :(得分:1)
首先,实际上,你没有得到你点击的按钮的值,你只是按原样设置它们。您需要处理表单,然后在会话中设置它们。其次,你真的不需要多个表单标签,你只需要一个。第三,进行一些初始化,(项目列表,会话本身等)。只需创建一个项目数组。粗糙和枪支的例子:(同页表格处理)
<?php
// initializations
session_start();
$_SESSION['maxItems'] = 2;
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
$item_list = array('item01' => 11, 'item02' => 22, 'item03' => 33);
// add
if(isset($_POST['add'])) {
$item = $_POST['add'];
$value = $item_list[$item];
if(count($_SESSION['cart']) >= $_SESSION['maxItems']) {
echo 'Your cart is full, sorry.';
} else {
$_SESSION['cart'][] = array('name' => $item, 'price' => $item_list[$item]);
}
}
// clear all
if(isset($_POST['remove_all'])) { $_SESSION['cart'] = array(); header('Location: '.$_SERVER['PHP_SELF']); }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PHP Final Project</title>
</head>
<body>
<form method="POST" action="">
<label>Item 01 for sale</label>
<button type="submit" name="add" value="item01">Add To Cart</button>
<br/>
<label>Item 02 for sale</label>
<button type="submit" name="add"value="item02">Add To Cart</button>
<br/>
<label>Item 03 for sale</label>
<button type="submit" name="add" value="item03">Add To Cart</button>
<br/><br/>
<input type="submit" name="remove_all" value="Clear Cart" />
</form>
<?php if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0): ?>
<div class="chosen_items">
<h3>Current Items</h3>
<?php foreach($_SESSION['cart'] as $key => $value): ?>
<p><?php echo "Item: <strong>". $value['name']. "</strong> Price: $".$value['price']; ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
</body>
</html>