Use PHP to build a form that will allow a user to type in the price of a candy i
ID: 3824128 • Letter: U
Question
Use PHP to build a form that will allow a user to type in the price of a candy in addition the number of quarters, dimes, and nickels they have. After the user submits their information, the form should tell them how much money they have, how many candies they can buy, and what their change will be. The form should check to make sure valid information was typed in (use is_numeric() and empty().) and let the user know if their info was wrong via output to the page.Add an input for pennies and let the user know what kind of change they would get back in quarters, dimes, nickels, and pennies.
Explanation / Answer
For the given problem we required fields like total money, the no of candies can buy.
It should validate whether the entered value is numeric or not. If validation fails it should display the message also.
Sample php code for the given problem given below
<form action="/action_page.php">
Total money: <input type="text" name="money" value="<?php echo $ money;?>">
No of candies that can buy <input type="text" name="noCandies" value="<?php echo $ noCandies;?>">
<input type="submit" value="Submit">
</form>
The validation code is given below
<?php
// define variables and set to empty values
$ moneyErr = $ moneyErr = $ moneyErr = $websiteErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["money"])) {
$nameErr = "money is required";
} else {
$name = test_input($_POST["money"]);
}
if(preg_match('/^d+$/',$_GET['id'])) {
// valid input.
} else {
// invalid input.
}
}
?>
This validation code will check the fields is filled or not and it will also check whether the field is taking integer or not
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.