Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - HTML form two possible actions?

Tags:

html

forms

php

I'm creating a registration page and I would like to give the user the opportunity to review their information and go back and edit it before clicking a confirm button which inserts it into the database.

Is there a way to include two submit buttons which point to different scripts or would I have to duplicate the entire form but use hidden fields instead?

Any advice appreciated.

Thanks.

like image 486
Dan Avatar asked Jul 01 '26 04:07

Dan


2 Answers

You can use two submit buttons with different names:

<input type="submit" name="next" value="Next Step">
<input type="submit" name="prev" value="Previous Step">

And then check what submit button has been activated:

if (isset($_POST['next'])) {
    // next step
} else if (isset($_POST['prev'])) {
    // previous step
}

This works because only the activated submit button is successful:

  • If a form contains more than one submit button, only the activated submit button is successful.
like image 132
Gumbo Avatar answered Jul 03 '26 22:07

Gumbo


As for every other HTML input element you can just give them a name and value pair so that it appears in the $_GET or $_POST. This way you can just do a conditional check depending on the button pressed. E.g.

<form action="foo.php" method="post">
    <input type="text" name="input">
    <input type="submit" name="action" value="Add">
    <input type="submit" name="action" value="Edit">
</form>

with

$action = isset($_POST['action']) ? $_POST['action'] : null;
if ($action == 'Add') {
    // Add button was pressed.
} else if ($action == 'Edit') {
    // Edit button was pressed.
}

You can even abstract this more away by having actions in an array.

like image 27
BalusC Avatar answered Jul 03 '26 22:07

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!