What are best practices for structuring forms in PHP to handle multiple submit buttons with different actions?
When dealing with forms in PHP that have multiple submit buttons with different actions, it is best to use conditional statements to determine which button was clicked and execute the corresponding action. This can be achieved by checking the value of the submit button in the form data when the form is submitted.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['button1'])) {
// Code to execute when button1 is clicked
} elseif (isset($_POST['button2'])) {
// Code to execute when button2 is clicked
}
}
?>
<form method="post" action="">
<!-- Form fields here -->
<button type="submit" name="button1" value="submit1">Button 1</button>
<button type="submit" name="button2" value="submit2">Button 2</button>
</form>