[php home]

Php_4: Using HTML Forms with PHP Variables (NUMBERS)

You can use a similar process to pass numbers from an HTML form to PHP. You will need to create the HTML forms page and write the PHP code that will carry out the task.

Create a page that will add two numbers together. Again, we could use any of the forms, but we will create two text boxes. Create your HTML page and save it as "addition.htm"

<html>
<head><title>form_php test page</title></head>
<body>

<form action="php_4.php" method="post">
First number: <input type="text" name="number1" size="10">
<p>
Second number: <input type="text" name="number2" size="10">

<input type="submit">
</form>

</body>
</html>

Create your PHP page and save as php_4.php.

<?php
$total = $_POST['number1'] + $_POST['number2'];
?>
<p>first number:
<?php
echo $_POST['number1'];
?>
<p>second number:
<?php

echo $_POST['number2'];
?>
<p>Total:
<?php

echo $total;
?>

Note: PHP uses the standard mathematic operators.
+ addition / - subtraction / * multiplication // division / ++ increment / -- decrement

Formatting Numbers:

Two frequently used PHP functions are "round()" and "number_format()"

The "round()" function will let you round to the closest integer (a number without decimal points)
$n = 23.333333;
$n = round ($n) ; // 23

or to a specified number of decimal places
$n = 23.333333;
$n = round ($n, 2) ; // 23.33

The "number_format()" function displays a number in a more frequently used format
$n = 123456;
$n = number_format ($n); // 123,456

or to specify a certain number of decimal points
$n = 123456;
$n = number_format ($n, 2); // 123,456.00

Exercise 4.1:
You are to set up a small online shopping page where the customer will enter the cost of two items. This information is to be sent to a PHP script that shows the purchased items, adds the purchased items together, adds a 5% shipping charge and then shows the total. Set your php page up so that all of the amounts are displayed in red.

Item 1 cost: xxxxxxxx
Item 2 cost: xxxxxxxx
subtotal: xxxxxxxx
Shipping Cost: xxxxxxxxxx
Total: xxxxxxxxx

Use the following method on your PHP page- note how both HTML and PHP are used together.

item 1 cost: $<?php echo $_POST['cost1']; ?><br>

Make sure that you format your total so that is has two decimal points.