Mike Muta
Mike Muta

Reputation: 121

Multiple submit buttons in form

I have a shopping cart and would like the option to remove an item from the cart. I do not want to use javascript. The items in the cart are looped through in php by grabbing the session variable, and displayed in a table with the option to remove the item. As of right now I have multiple input submits for the "remvove item" link, and inside my for loop I have these input tags which are generated with the ID of the item.

<input type="hidden" name="id[]" value="<?php echo $uniqueid; ?>
<input type="submit" name="remove" value="removeitem" class="otherbtns" />

My problem is in my script that handles the post variables has no way of knowing which "removeitem" link was clicked, hence removing the first one. I'm just kinda looking for the best way to handle soemthing like this without JS.

Thanks

Upvotes: 2

Views: 1331

Answers (5)

user1588255
user1588255

Reputation: 201

read your $id[$i] from database and save amount of records to $count then check if you need to delete something:

for ($i = 0; $i <= $count; $i++) {
  if (isset($_POST[$id[$i]])) { 
    remove your $id[$i] from database
  }
}

then read your $id[$i] from database again and save amount of records to $count

for ($i = 0 ; $i <= $count; $i++) {
  echo '<input type="submit" name="'.$id[$i]'." value="removeitem">';
}

Upvotes: 1

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

Use multiple forms. You can have as many forms as you want in your script, one submit per form. Do not take the path of using js to submit your form -> kittens will die if you do this.

Upvotes: 2

Jason
Jason

Reputation: 2727

You can handle this with a simple link to the same page, but in the $_GET gather the information and have it run through a script:

<a href="cart.php?remove=yes&item_to_remove=<?php echo item_id; ?>">Remove</a>

Then in the php script

if ( (isset($_GET['remove']))and($_GET['remove'] == 'yes') ){
   //then remove the item from the session var by removing the $_GET['item_to_remove']
}

Upvotes: 0

sdleihssirhc
sdleihssirhc

Reputation: 42496

If you don't mind exposing the id value to the user, a quick-n-dirty way to fix it would be changing the value attribute of each submit button:

<input type="submit" ... value="removeitem <?php echo $uniqueid ?>" />

Then, when the form is sent to the server, you can parse and check the value with PHP. Depending on how complicated your IDs are, you could do something as simple as this:

$value = $_POST['remove'];
$value = explode(' ', $value);
$value = $value[1];

...And that would theoretically give you the ID you need.

Upvotes: 0

Tyler Crompton
Tyler Crompton

Reputation: 12652

Could you possibly make multiple forms each with a different value for the action attribute?

Upvotes: 3

Related Questions