Reputation: 415
I'm trying to create button to a delete specific items out of my shopping cart, and so far it somewhat works. The problem is that it's not consistent. When I try to delete the 2nd item, it deletes the 3rd item, and when there are two items in the cart and I delete the second one, it doesn't do anything when the button is clicked. I must have missed something.
I have data being pulled out from my database, and I am starting i
at 1.
$i=1;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
This is what I have tried. My form looks like this..
<form action='cart.php' method='post'>
<input name='deleteBtn" . $item_id . "'type='submit' value='Remove This Item' />
<input name='index_to_remove' type='hidden' value='" . $i . "' /></form>
i++;
And to remove the item, I have:
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
} else {
unset($_SESSION["cart_array"]["$key_to_remove"]);
//In case I want it to sort - sort($_SESSION["cart_array"]);
}
}
Can you help?
Upvotes: 0
Views: 107
Reputation: 1318
you should use the index (keys) of the array. Arrays are lists of key=>value pairs:
foreach ($_SESSION["cart_array"] as $key => $each_item) {
...
}
Now use that key in your form:
<input name='index_to_remove' type='hidden' value='" . $key . "' />
And finaly unset the array_key (if it exists):
...
$key_to_remove = $_POST['index_to_remove'];
if(array_key_exists($key_to_remove, $_SESSION["cart_array"])){
unset($_SESSION["cart_array"][$key_to_remove]);
}
....
Suggestion: Since you have a (unique) item_id to start with, why not use that item_id as key (identifier) in your array to start with? Instead of having it in your values.
So this:
$_SESSION["cart_array"][0] = array(
'item_id' => 'IdOfYourItem',
'item_name' => 'nameOfYourItem',
'quantity' => 1,
'other_key' => 'otherValue'
);
could be this:
$_SESSION["cart_array"]['IdOfYourItem'] = array(
'item_name' => 'nameOfYourItem',
'quantity' => 1,
'other_key' => 'otherValue'
);
Upvotes: 0
Reputation: 44851
The code you have posted never increments $i
, so $_POST['index_to_remove']
is always 1
. This is going to delete $_SESSION["cart_array"]["1"]
every time.
It's impossible to tell from this code which item has index "1"
in $_SESSION["cart_array"]
, but the key point is that you are using the same value for $_POST['index_to_remove']
for every item.
Upvotes: 1