Home > Article > Backend Development > How do you Identify Which Button Was Clicked in a PHP Form Submission?
Identifying the Clicked Button in PHP Form Submissions
When working with PHP forms, identifying which button initiated the submission is crucial for handling different actions.
Determining Button Click via Form Submission Method
In a form using the POST method:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Something posted if (isset($_POST['btnDelete'])) { // btnDelete was clicked } else { // Assume btnSubmit was clicked (default) } }
In this case, the $_POST array will contain the name of the button that was clicked. If $_POST['btnDelete'] is set, it means that the "Delete" button was clicked. Otherwise, we assume that the "Save Changes" button was clicked.
Handling Multiple Buttons
For forms with multiple submit buttons:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Something posted if (isset($_POST['btnSubmit1'])) { // btnSubmit1 was clicked } else if (isset($_POST['btnSubmit2'])) { // btnSubmit2 was clicked } else { // Assume btnSubmit3 was clicked (default) } }
We iterate through the names of the submit buttons and check if the corresponding key exists in $_POST. Only buttons that appear later in the form HTML need to be explicitly checked. The first button should always be assumed to be the submitter unless we detect otherwise.
Additional Considerations
The above is the detailed content of How do you Identify Which Button Was Clicked in a PHP Form Submission?. For more information, please follow other related articles on the PHP Chinese website!