not able to delete item from cart

2020-05-06 11:20发布

问题:

i m asking it again so this is more specific.

     $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>';

in this index_to_remove is coming via a hidden input type in the form... i created a form with a remove button and via a hidden output field i passed the index of item that i want to remove from the cart and implemented this code.But its not working.......

      <?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']);
     }
 }

    ?>

回答1:

Replace this line

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

to

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

as it changes your index_to_remove value to "1" instead of the value from post.

also your html tag is not closed correctly.



回答2:

The problem is here:

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

In the second part you have =!""

This evaluates to $var equals not "" and thus returns always true (and sets $_POST['index_to_remove'] to true which is then used in your if) . I believe you were looking for either != or !== which mean is not equal to.



回答3:

Your html is broken

Change

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

To

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