How can you pass multiple values from buttons in a form in PHP?
When passing multiple values from buttons in a form in PHP, you can use the name attribute to differentiate between the buttons. By assigning different values to each button's name attribute, you can determine which button was clicked when the form is submitted. You can then use PHP to access the value of the clicked button and perform the appropriate action based on that value.
<form method="post" action="process_form.php">
<button type="submit" name="button1" value="value1">Button 1</button>
<button type="submit" name="button2" value="value2">Button 2</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['button1'])) {
$clickedButtonValue = $_POST['button1'];
// Perform action for Button 1
} elseif (isset($_POST['button2'])) {
$clickedButtonValue = $_POST['button2'];
// Perform action for Button 2
}
}
?>
Keywords
Related Questions
- Is it advisable to separate objects like links and categories into distinct classes in PHP development for better organization?
- How can a search form in PHP be properly constructed to avoid errors like "Invalid argument supplied for foreach()"?
- What security measures should be taken when passing user inputs to the system() function in PHP?