Tuesday, October 11, 2011

Simple Calculator in PHP

Code Example

code for calculator.html

<html>
  <head>
    <title>Calculator</title>
  </head>
  <body>
 <form action = "calculator.php">
   <table align="center" cellspacing="20">
  <tr>
   <td>Enter First No.:</td>
   <td><input type="text" name="firstno"></td> 
  </tr>
  <tr>
   <td>Enter Second No.:</td>
   <td><input type="text" name="secondno"></td>
  </tr>
  <tr>
   <td>Select function.</td>
   <td><select name="function">
     <option value="sum">Add</option>
     <option value="sub">Subtract</option>
     <option value="mul">Multiply</option>
     <option value="div">Divide</option>
     </select>
   </td>
  </tr>
  <tr>
   <td colspan="2" align = "center"><input type="submit" value="  Submit  ">  </td>
  </tr>
         </table>
    </form>  
</body>
</html>

code for calculator.php

<html>
<head>
   <title>Calculator</title>
</head>
<body>
 <?php
  $num1=$_GET["firstno"];
  $num2=$_GET["secondno"];
  $function=$_GET["function"];
  switch ($function)
  {
   case 'sum':
    echo $num1+$num2;
    break;
   case 'sub':
    echo $num1-$num2;
    break;
   case 'mul':
    echo $num1*$num2;
    break;
   case 'div':
    echo $num1/$num2;
    break;
   default:
    echo 'Please select a funtion';
  }
 ?>
</body>
</html>


No comments:

Post a Comment