无法从购物车中删除商品


not able to delete item from cart

我再问一次,所以这更具体。

     $cartOutput.='<form method="post" action="cart.php">
     <input type="submit"name="deletebtn'.$item_id.'" value="remove"/>
     <input type="hidden" name="index_to_remove" value="'.$i.'"</form>';

在此index_to_remove中,通过表单中的隐藏输入类型...我创建了一个带有删除按钮的表单,并通过隐藏的输出字段传递了要从购物车中删除的项目的索引并实现了此代码。但它不起作用...

      <?php
       /////////////////////////////////////////////////////////
        // if user wants to remove an item from cart
         ////////////////////////////////////////////////////////
          if(isset($_POST['index_to_remove']) && $_POST['index_to_remove']=!"")
         {  
         //access the array and rum code to remove that array index
             $key_to_remove=$_POST['index_to_remove'];
          if(count($_SESSION['cart_array'])<=1)
          {
               unset($_SESSION['cart_array']);
               sort($_SESSION['cart_array']);
           }
   else
      {
               unset($_SESSION["cart_array"][$key_to_remove]);
               sort($_SESSION['cart_array']);
               echo count($_SESSION['cart_array']);
     }
 }
    ?>

替换此行

if(isset($_POST['index_to_remove']) && $_POST['index_to_remove']=!"")

if(isset($_POST['index_to_remove']) && $_POST['index_to_remove']!="")

因为它将您的index_to_remove值更改为"1"而不是 Post 中的值。

此外,您的 HTML 标记未正确关闭。

问题就在这里:

if(isset($_POST['index_to_remove']) && $_POST['index_to_remove']=!"")

在第二部分中,你有=!">

这计算结果为 $var 等于不 ",因此返回始终为 true(并将 $_POST['index_to_remove'] 设置为 true,然后在您的 if 中使用(。我相信您正在寻找 != 或 !== 这意味着不等于。

你的 html 坏了

改变

<input type="hidden" name="index_to_remove" value="'.$i.'"</form>';

<input type="hidden" name="index_to_remove" value='$i'></form>';