How can PHP be used to calculate discounts based on user input in a form?
To calculate discounts based on user input in a form using PHP, you can first create a form with input fields for the original price and discount percentage. Then, upon form submission, retrieve the user input using PHP and calculate the discounted price. Finally, display the discounted price to the user.
<?php
if(isset($_POST['submit'])){
$original_price = $_POST['original_price'];
$discount_percentage = $_POST['discount_percentage'];
$discount_amount = $original_price * ($discount_percentage / 100);
$discounted_price = $original_price - $discount_amount;
echo "Original Price: $" . $original_price . "<br>";
echo "Discount Percentage: " . $discount_percentage . "%<br>";
echo "Discounted Price: $" . $discounted_price;
}
?>
<form method="post">
Original Price: <input type="number" name="original_price" required><br>
Discount Percentage: <input type="number" name="discount_percentage" required><br>
<input type="submit" name="submit" value="Calculate Discount">
</form>
Related Questions
- How can using reserved words in PHP variables impact the functionality of a script?
- What best practices should be followed when securing user input in PHP to prevent unexpected outputs or vulnerabilities?
- What is the recommended approach for formatting query results in PHP, SQL, or a combination of both?