Assitance with basic Calculator

Below I made a basic calculator that adds, subtracts, divides, and multiplies. The issue is, when I submit the values the results do not “echo” on the page. Below is the code i have created. Hoping someone can assist me with this one.


<html>
      <body>

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

   First number: <input type="number" name="digit1"> <br>
   OP: <input type="text" name="op"> <br>
   Second number: <input type="number" name="digit2"> <br>
 <input type="submit"><br>

</form>

<?php
  $digit1 = $_Post["digit1"];
  $digit2 = $_Post["digit2"];
  $op = $_Post["op"];

if($op == "+"){
  echo $digit1 + $digit2;
} elseif($op == "-"){
  echo $digit1 - $digit2;
}elseif($op == "*"){
  echo $digit1 * $digit2;
}elseif($op == "/"){
  echo $digit1 / $digit2;
}else{
  echo "invalid operator";
}
 ?>

  </body>
</html>



  • $_Post should be $_POST
  • Keep your php block on top and leave HTML on the bottom. Just echo variabeles between HTML like so:
<?php
 $name = 'Don';
 // ...
?>
<!doctype html>
<html>
    <head>
        <title>Hello world</title>
    </head>
    <body>
        <h1>Hello <?php echo $name; ?></h1>
    </body>
</html>
  • $_POST form variables do ONLY exist if you submit your form and the browser request the page again with the POST request method instead of the GET method. A good practice is to make a if statement that tests if the page is called in POST method before accessing your $_POST form variables.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Now we can use the $_POST variables from our form
}
1 Like

Bonus tip: to debug and see what will be inside the $_POST array you could use this line:

echo '<pre>' . print_r($_POST, true) . '</pre>';
1 Like

More bonus tips:

  1. Stop creating variables for nothing
  2. Never trust user input. Escape the form output with htmlspecialchars

Thank you All, your advice was on point, and my calculator is working!

Sponsor our Newsletter | Privacy Policy | Terms of Service