Simple PHP Budget [closed]
I'm trying to make a simple budget form. What I need is that if some item is checked the system adds the price of these item (and if unchecked that item again substract it's price of the total).
<form name="myform" method ='post'>
<input name="item" type="checkbox" value="flowers"/>
<input name="item" type="checkbox" value="animals"/>
</form>
And what I want is something like
if (item[1].checked) $total_price = $total_price + item[1];
And likewise
if (item[1].unchecked) $total_price = $total_price - item[1];
Here is a quick example of how you might implement the above. I have not tested it, but it is something to get started with.
<?php
$price_list = array(
'animals' => 100,
'flowers' => 50
);
// Has data from form been posted back?
if (!empty($_POST)) {
$total_price = 0;
foreach ($_POST['item'] as $item) {
// Is price available for item?
if (isset($price_list[ $item ]))
$total_price += $price_list[ $item ];
else
throw new Exception('Invalid item: ' . $item);
}
echo 'Total Price: ', $total_price;
// End script before form is shown again.
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Item Counter</title>
</head>
<body>
<form action="" method="post">
<input id="itemFlowers" name="item[]" type="checkbox" value="flowers"/>
<label for="itemFlowers">Flowers $<?php echo $price_list['flowers']; ?></label>
<input id="itemAnimals" name="item[]" type="checkbox" value="animals"/>
<label for="itemAnimals">Animals $<?php echo $price_list['animals']; ?></label>
<input name="submit" type="submit" value="Submit" />
</form>
</body>
</html>
精彩评论