This post explains you how to use two or more submit buttons in a single HTML form using PHP technology.
HTML Part:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <head><title>Two Submit buttons in a Single Form!</title></head> <body> <form action="" method="post"> <h2>Two Submit Button with PHP</h2> <input type="submit" name="submit1" value="btn1" /> <input type="submit" name="submit2" value="btn2" /> </form> </body> </html> |
See the above code, there are two button I have used in the form,
First button with the name = “submit1”
Second button with the name = “submit2”
So, basically on submitting the form I’m going to check which button is clicked with the help of PHP program.
Here is the code for that:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php if(isset($_POST['submit1']) != '') { echo "You pressed button 1"; } if(isset($_POST['submit2']) != '') { echo "You pressed button 2"; } ?> |
The PHP code is simpler than you expected right?. Yes, of course, a simple IF condition can help you to find out which button is pressed. When you press the first submit button the form POST method will send value “btn1” to the server and when you press the second button it will send value = “btn2” to the server.
So, basically with the IF condition, you can check which of the button value is empty and which one has a value, then do the required operations you want with that. I’m here just printing the strings “you pressed button 1” or “you pressed button 1”.
Here is the entire code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php if(isset($_POST['submit1']) != '') { echo "You pressed button 1"; } if(isset($_POST['submit2']) != '') { echo "You pressed button 2"; } ?> <html> <head><title>Two Submit buttons in a Single Form!</title></head> <body> <form action="" method="post"> <h2>Two Submit Button with PHP</h2> <input type="submit" name="submit1" value="btn1" /> <input type="submit" name="submit2" value="btn2" /> </form> </body> </html> |
Also to see how the code works, see the DEMO here: