我在侧边栏中有一个简单的表格,在 5 页上,我有两个字段名称和价格。我想在用户提交表单时将其值保存在会话中。当我在提交表单后将其值存储在会话中时,它每次都会替换名称。但是我想像数组一样存储名称值。如果用户使用名称 user1 提交表单,然后使用用户名 user2 再次提交,那么我想在会话变量中显示这两个名称,并希望显示表单提交的增量。比如购物车功能。有没有办法用单个表单存储这些值。请帮助我。
<form id="myform" action="post.php" method="POST">
<div class="row">
<label for="name">Your name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="30" /><br />
</div>
<div class="row">
<label for="price">Price:</label><br />
<input id="price" class="input" name="price" type="text" value="" size="30" /><br />
</div>
<input id="submit_button" type="submit" value="submit" />
</form>
post.php
session_start();
$_SESSION['cart_items'] = array();
$_SESSION['cart_items'] = $_POST['name'];
foreach($_SESSION["cart_items"] as $cart_item)
{
echo $cart_item;
}
尝试通过以下方式向会话添加值
session_start();
foreach ($_SESSION["products"] as $cart_itm) //loop through session array
{
if($cart_item["code"] == $product_code){ //the item exist in array
$product[] = array('name'=>$cart_item["name"], 'code'=>$cart_item["code"], 'qty'=>$product_qty, 'price'=>$cart_item["price"]);
$found = true;
}else{
//item doesn't exist in the list, just retrieve old info and prepare array for session var
$product[] = array('name'=>$cart_item["name"], 'price'=>$cart_item["price"]);
}
}
将结果添加方式为
foreach ($_SESSION["cart"] as $cart_item)
{
echo $cart_item["price"];
$subtotal = ($cart_item["price"]*$cart_item["qty"]);
$total = ($total + $subtotal);
}
echo $total;