Comment déterminer quel bouton a été cliqué dans un formulaire PHP avec plusieurs boutons de soumission ?

DDD
Libérer: 2024-11-14 17:34:02
original
481 Les gens l'ont consulté

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)
    }
}
Copier après la connexion

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">
Copier après la connexion

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)
}
Copier après la connexion

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal