Unset session variable on button click event

给你一囗甜甜゛ 提交于 2019-12-12 01:06:33

问题


I can't unset a session variable properly using a "remove button" click. I have two pages: product page and shopping cart page, but problem is that I have a "remove button" in the shopping cart which is not working properly.

When I click on "remove button" it should run unset($_SESSION['product1'].

But when I select another item then it can display "previous session item" so it means remove button does not run unset($_SESSION['product1'] properly. How do I solve this issue?

Product Page

session_start();
$id=$_REQUEST['id'];
$_SESSION['pid1']= $_POST['ids']; //Product ID//
$_SESSION['product1'][]=$_POST['product'];

<form method="post">
<input type="hidden" name="product[]" value="<?php echo $row1['product']; ?>" />
<input type="hidden" name="ids" value="<?php echo $id?>" />
</form>

<input type="submit" class="button1" name="addtocart" value="Add To Cart"
/>

</form>

Shopping Cart Page

session_start();
$pid=$_SESSION['pid1'];   

function remove_product($pid){
$pid=intval($pid);
$max=count($_SESSION['product1']);
for($i=0;$i<$max;$i++){
if($pid==$_SESSION['product1'][$i]['pid']){
unset($_SESSION['product1'][$i]);
break;
}
}
$_SESSION['product1']=array_values($_SESSION['product1']);
}

if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){
remove_product($_SESSION['product1'][$pid]);
}



<form  name="form1" method="post">  
<input type="hidden" name="pid" />
<input type="hidden" name="command" />  

<input type="button" class="button2" value="Remove" 
onclick="javascript:del(<?php echo $pid?>)"/>

Shopping Cart Page Javascript

<script language="javascript">
function del(pid){
if(confirm('Do you really mean to delete this item')){
document.form1.pid.value=pid;
document.form1.command.value='delete';
document.form1.submit();
}
}

function clear_cart(){
if(confirm('This will empty your shopping cart, continue?')){
document.form1.command.value='clear';
document.form1.submit();
}
}
</script>

回答1:


It might be caused by

  1. $pid=$_SESSION['pid1']; instead of $pid=$_POST['pid1'];

  2. event that is tied to tag wrapped around a button, you coud just use

<input type="button" class="button2" value="Remove" onclick="del('<?php echo $pid?>');"/>



来源:https://stackoverflow.com/questions/16164437/unset-session-variable-on-button-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!