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.4 - calculator.php
10. /* This script displays and handles an HTML form.
11. It uses a function to calculate a total from a quantity and price. */
12.
13. // This function performs the calculations.
14. function calculate_total ($quantity, $price) {
15.
16. $total = $quantity * $price; // Calculation
17. $total = number_format ($total, 2); // Formatting
18.
19. return $total; // Return the value.
20.
21. } // End of function.
22.
23. // Check for a form submission:
24. if (isset($_POST['submitted'])) {
25.
26. // Check for values:
27. if ( is_numeric($_POST['quantity']) AND is_numeric($_POST['price']) ) {
28.
29. // Call the function and print the results:
30. $total = calculate_total($_POST['quantity'], $_POST['price']);
31. print "<p>Your total comes to $<span style=\"font-weight: bold;\">$total</span>.</p>";
32.
33. } else { // Inappropriate values entered.
34. print '<p style="color: red;">Please enter a valid quantity and price!</p>';
35. }
36.
37. }
38. ?>
39. <form action="calculator.php" method="post">
40. <p>Quantity: <input type="text" name="quantity" size="3" /></p>
41. <p>Price: <input type="text" name="price" size="5" /></p>
42. <input type="submit" name="submit" value="Calculate!" />
43. <input type="hidden" name="submitted" value="true" />
44. </form>
45. </body>
46. </html>
47.