Home > Article > Backend Development > How do you determine which button was clicked in a PHP form with multiple submit buttons?
How to Determine the Originating Button in a PHP Form Submission
When designing forms with multiple submit buttons, it becomes crucial to identify which button was clicked upon form submission. This section presents a comprehensive guide to assist developers in achieving this functionality.
Identifying the Submit Button
To differentiate between the submit buttons, PHP utilizes the following approach:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['btnDelete'])) { // btnDelete was clicked } else { // Default to the first submit button (btnSubmit) } }
Consider Default Submit Button
It's essential to acknowledge that the first submit button appearing in the form HTML is considered the default submitter. This principle applies to both single and multi-button forms.
Example: Multi-Button Form
Assuming the following form markup:
<input type="submit" name="btnSubmit1" value="1"> <input type="submit" name="btnSubmit2" value="2"> <input type="submit" name="btnSubmit3" value="3">
PHP code would determine the clicked button as follows:
if (isset($_POST['btnSubmit3'])) { // btnSubmit3 was clicked } elseif (isset($_POST['btnSubmit2'])) { // btnSubmit2 was clicked } else { // Default to btnSubmit1 (first submit button) }
GET Method Considerations
For forms using the GET method, employing $_SERVER['REQUEST_METHOD'] === 'GET' is unreliable. Instead, consider adding a hidden input named 'submitted' and setting its value to 1. This allows for submission detection via isset($_GET['submitted']).
Browser Compatibility
This approach enjoys excellent browser compatibility, extending support to browsers from the early 2000s and beyond. Its logical structure is easily adaptable to other languages.
The above is the detailed content of How do you determine which button was clicked in a PHP form with multiple submit buttons?. For more information, please follow other related articles on the PHP Chinese website!