Two submit buttons in one form

Alex picture Alex · Feb 13, 2009 · Viewed 625.4k times · Source

I have two submit buttons in a form. How do I determine which one was hit serverside?

Answer

Parrots picture Parrots · Feb 13, 2009

Solution 1:
Give each input a different value and keep the same name:

<input type="submit" name="action" value="Update" />
<input type="submit" name="action" value="Delete" />

Then in the code check to see which was triggered:

if ($_POST['action'] == 'Update') {
    //action for update here
} else if ($_POST['action'] == 'Delete') {
    //action for delete
} else {
    //invalid action!
}

The problem with that is you tie your logic to the user-visible text within the input.


Solution 2:
Give each one a unique name and check the $_POST for the existence of that input:

<input type="submit" name="update_button" value="Update" />
<input type="submit" name="delete_button" value="Delete" />

And in the code:

if (isset($_POST['update_button'])) {
    //update action
} else if (isset($_POST['delete_button'])) {
    //delete action
} else {
    //no button pressed
}