Thursday, 12 January 2012

Multiple submit buttons in a Form in PHP explain with an example

Hi friends, today I am discussing handling multiple submit buttons in a single Form in PHP.
According to typical HTML architecture there have one submit button for a Form.When this submit button  is clicked the php page specified by the form action parameter is loaded.

          But some situations we need multiple submit buttons in a single form.In such situations the php page loaded by clicking distinct buttons is same.But the task executed will be different.We can achieve it by isset()  function of PHP.
          The syntax for isset() is : isset($_POST["name of submit button in the form"])

We can write the  code for the action page like this:-
echo "You pressed submit 1";

else if(isset($_POSt["s2"]))
echo "You pressed submit 2";

Where s1 and s2 are the name of submit buttons in the form.

Here I am including a simple calculator example to clear  this concept

This is a screen shot of the program:

Source code

<form name="f1" method="post" action="sub.php">
Number1 <input type="text" name="n1"></br></br>
Number2 <input type="text" name="n2">
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mul" value="*">
<input type="submit" name="div" value="/">



echo "Sum : ".($_POST["n1"]+$_POST["n2"]);

else if(isset($_POST["sub"]))
echo "Difference : ".($_POST["n1"]-$_POST["n2"]);

else if(isset($_POST["mul"]))
echo "Product : ".($_POST["n1"]*$_POST["n2"]);

else if(isset($_POST["div"]))
echo "Quotient : ".($_POST["n1"]/$_POST["n2"]);

code description:

In calculator.html we can see a form.There have 2 text boxes and 4 submit buttons.The two submit buttons are the
two numbers to perform arithmetic operations.The four submit buttons are for additon,substraction,multiplication and division.
The name of the submit buttons are add,sub,mul,div respectively.

       In sub.php four if else statements are used to determine which submit button is clicked.
First if is:
Where 'add' is the name of first submit button.isset($_POST["add"])  return TRUE if the submit button clicked is 'add'.If it return true 
echo "Sum : ".($_POST["n1"]+$_POST["n2"]); 
this statement will execute.So the sum of given numbers will be displayed.
If isset() returns FALSE go to the next if statement and check for the click of next submit button.This process will be continued till the clicked button is found.Thus our calculator works properly.

isset() is the standard way to achieve this but we can simply write
echo "Sum : ".($_POST["n1"]+$_POST["n2"]);

for achive the same result.

Hope that this post is helpful to you.Thanks by Sukesh B R


  1. thanks.but i need save and upload button on single form and its codding

  2. yes, I am also need insert and update button for mysql process

  3. thanks good example!,appreciated.


Search This Blog