$page_title = 'Widget Cost Calculator';
include ('../includes/header.html');
// This function calculates the total and prints the results. We have made the $tax argument optional for the user. It now has a default value.
function calculate_total ($qty, $cost, $tax = 5) {
$total = ($qty * $cost);
$taxrate = ($tax / 100); // Turns 5% into 05.
$total += ($total * $taxrate); // Add the tax
return number_format($total, 2);
} // end of function
// Check the form submission
if (isset($_POST['submitted'])) {
// Minimal form submission
if ( is_numeric($_POST['quantity']) && is_numeric($_POST['price']) ) {
// Print the heading
echo '
Total Cost
';// Call the function with or without tax:
if (is_numeric($_POST['tax'])) {
$sum = calculate_total ($_POST['quantity'], $_POST['price'], $_POST['tax']);
} else {
$sum = calculate_total ($_POST['quantity'], $_POST['price']);
}
// print the results:
echo 'The total cost of purchasing ' . $_POST['quantity'] . ' Widget(s) at £' . number_format ($_POST['price'], 2) . ' each, with tax, is £' . $sum . '.
';
} else { // invalid submitted values:
echo '
Error!
Please enter a valid quantity and price.
';}
} // end of main isset() IF.
// Leave the PHP section and create the HTML form:
?>
Widget Cost Calculator
Quantity:
Price:
Tax (%): (Optional)
include ('../includes/footer.html');
?>
No comments:
Post a Comment