Skip to content
Advertisement

How can I echo a statement from a form?

I’m a student doing a challenge where I would have to make a Calculator-type form where you can input two values and click an operation. It’s a simple concept using only 4 operations.

I was able to make the format of the form: title, input text and buttons. But I can’t find a way to take the input information and manipulating the information. My initial goal was to take the two values and adding/subtracting/multiplying/dividing the values and printing the statement above.

For example:

1 + 2 = 3 //statement printed above

First Value: 1 Second Value: 2 //insert values

+ - * / //click operation buttons

Any suggestions?

<!DOCTYPE HTML>

<?php
  print_r($_POST);
  if ( isset($_POST["+"]) ) {
    $sum = $var1 + $var2;
    echo "$var1 + $var2 = $sum";
  }
  elseif( isset($_POST["-"]) ) {
    $sum = $var1 - $var2;
    echo "$var1 - $var2 = $sum";
  }
  elseif ( isset($_POST["*"]) ) {
    $sum = $var1 * $var2;
    echo "$var1 * $var2 = $sum";
  }
  elseif ( isset($_POST["/"]) ) {
    $sum = $var1 / $var2;
    echo "$var1 / $var2 = $sum";
  }
?>

<html>
   <body>
     <form action="" method="POST">
      First Value: <input type="text" name="First Value"><br><br>
      Second Value: <input type="text" name="Second Value"><br><br>
      Operations: <button type="submit" name "+">+</button>
                  <button type="submit" name "-">-</button>
                  <button type="submit" name "*">*</button>
                  <button type="submit" name "/">/</button>
     </form>
  </body>

</html>

Advertisement

Answer

This seems to fix the errors I mentioned in comments

<!DOCTYPE HTML>
<html>
<body>
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){
  
  if ( isset($_POST["+"]) ) {
    $sum = $_POST['var1'] + $_POST['var2'];
    echo "$_POST[var1] + $_POST[var2] = $sum";
  }
  elseif( isset($_POST["-"]) ) {
    $sum = $_POST['var1'] - $_POST['var2'];
    echo "$_POST[var1] - $_POST[var2] = $sum";
  }
  elseif ( isset($_POST["*"]) ) {
     $sum = $_POST['var1'] * $_POST['var2'];
    echo "$_POST[var1] * $_POST[var2] = $sum";

  }
  elseif ( isset($_POST["/"]) ) {
    $sum = $_POST['var1'] / $_POST['var2'];
    echo "$_POST[var1] / $_POST[var2] = $sum";

  }
}
?>

     <form action="" method="POST">
      First Value: <input type="text" name="var1"><br><br>
      Second Value: <input type="text" name="var2"><br><br>
      Operations: <button type="submit" name="+">+</button>
                  <button type="submit" name="-">-</button>
                  <button type="submit" name="*">*</button>
                  <button type="submit" name="/">/</button>
     </form>
</body>
</html>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement