Two submit buttons in one form

Solution 1:

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
}

Solution 2:

If you give each one a name, the clicked one will be sent through as any other input.

<input type="submit" name="button_1" value="Click me">

Solution 3:

An even better solution consists of using button tags to submit the form:

<form>
    ...
    <button type="submit" name="action" value="update">Update</button>
    <button type="submit" name="action" value="delete">Delete</button>
</form>

The HTML inside the button (e.g. ..>Update<.. is what is seen by the user; because there is HTML provided, the value is not user-visible; it is only sent to server. This way there is no inconvenience with internationalization and multiple display languages (in the former solution, the label of the button is also the value sent to the server).

Solution 4:

There’s a new HTML5 approach to this, the formaction attribute:

<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>

Apparently this does not work in Internet Explorer 9 and earlier, but for other browsers you should be fine (see: w3schools.com HTML <button> formaction Attribute).

Personally, I generally use JavaScript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are Internet Explorer before version 9 with JavaScript disabled.

Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.

As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.

Solution 5:

This is extremely easy to test:

<form action="" method="get">
    <input type="submit" name="sb" value="One">
    <input type="submit" name="sb" value="Two">
    <input type="submit" name="sb" value="Three">
</form>

Just put that in an HTML page, click the buttons, and look at the URL.