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.
위 내용은 제출 버튼이 여러 개인 PHP 양식에서 어떤 버튼이 클릭되었는지 어떻게 확인합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!