Calculation based on form data : Form Data « Form « PHP






Calculation based on form data

 
<html>

 <head> 
  <title>Calculation Form</title> 
 </head>

 <body>

  <form action = "calc.php" method = "post">

  Value 1: <input type = "text" name = "val1" size = "10">
  Value 2: <input type = "text" name = "val2" size = "10">
  <br>
  Calculation: <br>
  <input type = "radio" name = "calc" value = "add"> Add
  <input type = "radio" name = "calc" value = "sub"> Subtract
  <input type = "radio" name = "calc" value = "mul"> Multiply
  <input type = "radio" name = "calc" value = "div"> Divide 
  <hr>
  <input type = "submit" value = "Calculate"> 
  <input type = "reset" value = "Clear">

  </form>

 </body>

</html>


File: calc.php




<html> 
 <head> 
  <title>Calculation Result</title> 
 </head>
 <body>

 <?php 

  $val1 = $_POST['val1'];
  $val2 = $_POST['val2'];
  $calc = $_POST['calc'];

  if( is_numeric( $val1 ) && is_numeric( $val2 ) )
  {
      if( $calc != null )
      {
          switch( $calc )
          {
              case "add" : $result = $val1 + $val2; break;
              case "sub" : $result = $val1 - $val2; break;
              case "mul" : $result = $val1 * $val2; break;
              case "div" : $result = $val1 / $val2; break;
          }      
        echo( "Calculation result: $result" );
      } 
  }
  else
  { 
    echo( "Invalid entry - please retry" ); 
  }
 ?>

 </body>
</html>
  
  








Related examples in the same category

1.Deal with Array Form Data
2.A process_form() Function
3.Access widget's form value
4.Accessing multiple submitted values
5.Forms and PHP
6.Feedback Form
7.Handling Special Characters
8.multivalue-forms.php
9.Saying "Hello"