How can multiple buttons in a form pass different data to separate PHP scripts?
To pass different data to separate PHP scripts based on which button is clicked in a form, you can use the "name" attribute on the buttons to differentiate them. Then, in the PHP script that processes the form submission, you can check which button was clicked using the $_POST superglobal and execute the corresponding code based on that.
<form method="post" action="process.php">
<button type="submit" name="button1" value="data1">Button 1</button>
<button type="submit" name="button2" value="data2">Button 2</button>
</form>
```
In the "process.php" script:
```php
if(isset($_POST['button1'])) {
// Process data for Button 1
$data = $_POST['button1'];
// Additional code for Button 1
} elseif(isset($_POST['button2'])) {
// Process data for Button 2
$data = $_POST['button2'];
// Additional code for Button 2
}
Related Questions
- What are the best practices for handling PHP variables and ensuring they are defined before use?
- How can PHP developers prevent SQL injection vulnerabilities when retrieving user data based on IDs from URLs?
- What are some recommended resources or libraries for sending emails with attachments in PHP?