首页 > 解决方案 > 如何根据 id PHP 从会话数组中删除变量

问题描述

添加产品后,我试图从我的购物车中删除产品。

你能帮忙吗

这是我的代码

添加到购物车

html:

<input type="hidden" name="pid" value="<?php echo $row['product_id']?>
<input type="double" name="weight" placeholder="Weight?" required>

PHP:

session_start();

$pid = $_POST['pid'];
$weight = $_POST['weight'];

$p = "pid";
$p .= (string) $pid;
$w = "weight";
$w .= (string) $pid;

$_SESSION[$p]=$pid;
$_SESSION[$w] = $weight;

if(isset($_SESSION)){
  header('location:../shopping-cart.php');
}

执行后添加产品。

显示在购物车中

foreach($_SESSION as $key => $values){
    if(strpos($key, "pid") !== false){
        $sql="select * from products where product_id = $_SESSION[$key]";
        $result=$connect->query($sql);
        $r = mysqli_fetch_assoc($result);

        $w = "weight";
        $w .= (string) $r['product_id'];
        $weight = $_SESSION[$w];

HTML PHP 代码

<?php echo $r["product_name"];?>    
<?php echo 'LBP '.number_format($r['product_price'],0)?>
<input type="hidden" id="unitprice" onchange="f();" value="<?php echo $r['product_price']?>">
<input type="text" onchange="f();" id="quantity" value="<?php echo $weight ?>">
<input type="submit" value="Delete">
<input type="hidden" name="pid" value="<?php echo $r['product_id'] ?>">
<input type="hidden" name="pweight" value="<?php echo $weight ?>">

从购物车中删除不起作用任何帮助?

session_start();


    $pidremove = $_POST['pid'];
    $weightremove = $_POST['pweight'];


foreach($_SESSION as $key => $values){
   if($_SESSION[$w]==$pidremove)
   {
       unset($_SESSION[$w]);
       unset($_SESSION[$p]);
       echo 'done';
   }

}

标签: phphtmlsql

解决方案


HTML:

<input type="hidden" name="pid" value="<?php echo $row['product_id']; ?>" />
<input type="submit" name="remove" value="Remove">

PHP:

unset($_SESSION['pid' . $_POST['pid']]
unset($_SESSION['weight' . $_POST['pid']]

推荐阅读