Reputation: 39
Hey there I'm trying to learn some PHP since 2 weeks. Right now I try to build an Interest calculator which calculates the final capital. The calculator works perfectly fine. But my form checkup works not the way I want it to behave. First, it should check if the input types are filled in. After that, it should check if negative values are filled in. After that, if only positive values are given it should start to calculate. Does anybody know how to do that?
<form action="#" method="get">
<div>Interest calculator</div><br>
<span>Initial capital</span>
<input type="text" name="capital"><br><br>
<span>Run time in years</span>
<input type="text" name="runtime"><br><br>
<span>Interest rate in %</span>
<input type="text" name="rate"><br><br>
<input type="submit" value="Calculate final capital">
</form>
<?php
if (empty($_GET["capital"] || $_GET["runtime"] || $_GET["rate"]))
{
echo "Please insert a value";
}
else
{
if ($A <=0 || $L <=0 || $Z <=0)
{
$A=$_GET["capital"];
$L=$_GET["runtime"];
$Z=$_GET["rate"];
echo "No negative values may be entered.";
}
if ($A >0 && $L >0 && $Z >0)
{
$Z=$Z/100;
$Z=1+$Z;
for($i=1; $i<=$L; $i++) $A=bcmul($A,$Z,2);
echo "The final capital is: " .$A ."€" ;
}
}
?>
Upvotes: 0
Views: 58
Reputation: 5316
Couple of things to improve your code:
type="text"
to type="number"
to simplify the user input;empty()
is considering 0
also as false
, better use is_numeric()
;$_GET
in order to display respective messages only upon submit;0
values are considered also as invalid, better inform the user about it;<div>Interest calculator</div>
<br>
<form action="#" method="get">
<span>Initial capital</span>
<input type="number" name="capital"><br><br>
<span>Run time in years</span>
<input type="number" name="runtime"><br><br>
<span>Interest rate in %</span>
<input type="number" name="rate"><br><br>
<input type="submit" value="Calculate final capital">
</form>
<?php
if(!empty($_GET)) {
if (!is_numeric($_GET["capital"]) || !is_numeric($_GET["runtime"]) || !is_numeric($_GET["rate"])) {
echo "Please insert numeric values";
} else {
$A = $_GET["capital"];
$L = $_GET["runtime"];
$Z = $_GET["rate"];
if ($A <= 0 || $L <= 0 || $Z <= 0) {
echo "No negative or zero values may be entered.";
} else {
$Z = $Z / 100;
$Z = 1 + $Z;
for ($i = 1; $i <= $L; $i++) {
$A = bcmul($A, $Z, 2);
}
echo "The final capital is: " . $A . "€";
}
}
}
?>
If you need to accept not only integer values in your input
fields, you can use step
tag into:
<input type="number" step="0.01">
Upvotes: 1