【发布时间】:2014-07-30 15:07:40
【问题描述】:
我正在尝试做一个购物车项目。我认为根据我为产品列表中的项目设置表单的方式,只有已选择的项目才会显示在购物车中,但无论我点击哪一个,它都会显示所有三个项目。谁能告诉我我需要改变什么。
列出产品的主页:
<?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>
【问题讨论】:
-
您在 html 中创建会话,因此即使用户没有提交表单也会在页面加载时!!
标签: php forms session shopping-cart