[英]Using session as a temporary cart
im building a website where in it i need to have a temporary cart, client doesnt want database so i have to deal with it by sessions. 即时通讯建立一个网站,在其中我需要一个临时的购物车,客户不需要数据库,所以我必须通过会话来处理它。 so here comes my question:
所以这是我的问题:
I have already set up a form which sends post actions to another php file and gets redirected to another page after action, i want the form to get added to the session as a new array on every submit, so i can show all cart details at checkout, but even when i use array_push i cant get it to work, it overwrites the previous array: 我已经设置了一个表单,该表单将后操作发送到另一个php文件,并在操作后重定向到另一个页面,我希望该表单在每次提交时都作为新数组添加到会话中,因此我可以在结帐,但是即使我使用array_push我也无法使其正常工作,它会覆盖先前的数组:
<form class="form-grey" action="<?php bloginfo('template_directory'); ?>/add_cart.php" method="POST">
<input type="hidden" name="bikeName" value="<?php the_title(); ?>">
<div class="row">
<div class="col-sm-3">
<label>Rent From:</label>
<input type="text" id="fromDate" name="fromDate" class="datepicker">
</div>
<div class="col-sm-3">
<label>Rent To:</label>
<input type="text" id="toDate" name="toDate" class="datepicker" disabled>
<button type="submit" name="Submit" class="btn btn-yellow">Add to Cart<span>+</span></button>
I have shortened the html code. 我已经缩短了html代码。
this is my add_cart.php 这是我的add_cart.php
<?php
session_start();
$_SESSION['cart'] = array();
$posts = array(
'fromDate' => $_POST['fromDate'],
'toDate' => $_POST['toDate'],
'bikeName' => $_POST['bikeName'],
'cyclistName' => $_POST['cyclistName'],
'height' => $_POST['height'],
'pedals' => $_POST['pedals'],
'helmets' => $_POST['helmets'],
'total' => $_POST['total']
);
array_push($_SESSION['cart'], $posts);
header("Location: http://localhost:5555/mbr/checkout");
die();
?>
errm, are you trying to add multiple products to a cart upon each form submission? errm,您是否要在每次提交表单时将多个产品添加到购物车? Because your
$_session['cart']
data is being reset each time the shown code runs with the line 因为每次显示的代码与该行一起运行时,您的
$_session['cart']
数据都会被重置
$_SESSION['cart'] = array();
is meaning the cart array is empty. 表示购物车数组为空。 Anything that was previously in it has been cleared.
之前的所有内容均已清除。
Solution: delete this line. 解决方案:删除此行。
You must first check that the session isn't already set, and only define $_SESSION['cart']
as an empty array if it isn't. 您必须首先检查该会话是否尚未设置,并且如果未将
$_SESSION['cart']
定义为空数组,则必须将其定义为空数组。 else you would be continuously overwriting an empty array. 否则您将不断覆盖一个空数组。
if(!isset($_SESSION['cart']){
$_SESSION['cart'] = array();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.