1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4. <head>
5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
6. <title>Cost Calculator</title>
7. </head>
8. <body>
9. <?php // Script 10.5 - calculator.php #2
10. /* This script displays and handles an HTML form.
11. It uses a function to calculate a total from a quantity, price, and tax rate. */
12.
13. // Define a tax rate:
14. $tax = 8.75;
15.
16. // This function performs the calculations.
17. function calculate_total ($quantity, $price) {
18.
19. global $tax;
20.
21. $total = $quantity * $price; // Calculation
22. $taxrate = ($tax / 100) + 1;
23. $total = $total * $taxrate; // Add the tax.
24. $total = number_format ($total, 2); // Formatting
25.
26. return $total; // Return the value.
27.
28. } // End of function.
29.
30. // Check for a form submission:
31. if (isset($_POST['submitted'])) {
32.
33. // Check for values:
34. if ( is_numeric($_POST['quantity']) AND is_numeric($_POST['price']) ) {
35.
36. // Call the function and print the results:
37. $total = calculate_total($_POST['quantity'], $_POST['price']);
38. print "<p>Your total comes to $<span style=\"font-weight: bold;\">$total</span>, including the $tax percent tax rate.</p>";
39.
40. } else { // Inappropriate values entered.
41. print '<p style="color: red;">Please enter a valid quantity and price!</p>';
42. }
43.
44. }
45. ?>
46. <form action="calculator.php" method="post">
47. <p>Quantity: <input type="text" name="quantity" size="3" /></p>
48. <p>Price: <input type="text" name="price" size="5" /></p>
49. <input type="submit" name="submit" value="Calculate!" />
50. <input type="hidden" name="submitted" value="true" />
51. </form>
52. </body>
53. </html>
54.