Let's learn how to make an html form and connect the form up to a php worker file to process the form for our users.

To make the form we'll add a new file to our Introduction to PHP app called maths.php. In the file we'll add our html tags including our new form


<html>
<body>
<h1>Add em Up</h1>
<form method="post" action="bin/add.php">
  <label name="first number" />
  <input type="number" name="num1" />
  +
  <label name="second number" />
  <input type="number" name="num2" />
  <input type="submit" name="=" value="=" />
</form>
</body>
</html>

The new things for us here are the form and input html elements.

The form element has a method attribute and an action attribute.

The method for this form is set to post this tells the form to collect all the sumbitted data into the php $_POST variable. Then in our php action file we can retrieve the data from $_POST for processing.

The action attribute is set to bin/add.php which tells the browser when the use hits the submit button to use the file bin/add.php to process the data and return a result (a web page) to the user.

The input input elements are what collects data from the users of the maths.php page. Once a user enters data and submits the form we can then retrieve that data from the $_POST variable based on the name that we give the input elements, in this case we have named them num1 and num2.

The add.php file is what the form calls to do the processing. You should create a bin directory in your Introduction to PHP app and inside the bin directory create a file called add.php. In the add.php file either type or copy and paste the following code:


<?php
  function add(int $num1, int $num2) {
    return $num1 + $num2;
  }
?>

<html>
<body>
<h1>Answer</h1>
<div class="answer">
  <?php print add($_POST['num1'], $_POST['num2']); ?>
</div>
<div>
  <a href="/maths.php">Back to Add em Up</a>
</div>
</body>
</html>

<style>
.answer {
  text-align: center;
  font-size: 23rem;
}
</style>


Now when a user submits the form it will call the bin/add.php file which will read in the $_POST array and in turn we can pass the elements $_POST['num1'] and $_POST['num2'] into our new add(int $num1, int $num2) function. Then we call the function inside our html which adds the numbers and then displays the answer to our users!