I am currently working with an simple php code with validation and this is my code:
<form action="" method="post">
<input type="text" name="name" id="name" placeholder="Name">
<br>Number of Books:<select id="books" name="books">
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
<option> 4 </option>
<option> 5 </option>
<option> 6 </option>
<option> 7 </option>
<option> 8 </option>
<option> 9 </option>
<option> 10 </option>
</select>
</br>dutedate <input type="date" name="duedate" id="duedate" placeholder="duedate">
</br>borrow <input type="date" name="datebor" id="datebor" placeholder="dateborrowed">
</br>return <input type="date" name="ret" id="ret" placeholder="date returned">
<input type="submit" class="button" name="btnsubmit" value="Submit">
</form>
<?php
if (isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$duedate = date_create(($_POST['duedate']));
$datebor = date_create(($_POST['datebor']));
$ret = date_create(($_POST['ret']));
$books = $_POST['books'];
$NOWdate = new Datetime('now');
if ($duedate < $datebor)
{
echo "<script>alert('Wrong Input Error1')</script>";
exit;
}
elseif ($datebor > $ret)
{
echo "<script>alert('Wrong Input Error2')</script>";
exit;
}
elseif ($datebor > $NOWdate )
{
echo "<script>alert('Wrong Error3')</script>";
exit;
}
elseif ($ret < $duedate)
{
$penalty = 0 ;
}
else
{
$penaltydays = date_diff($duedate,$ret) ;
$diff_date = $penaltydays->format('%a');
$penalty = $diff_date * $books * 10;
}
}
?>
<p>Penalty: <?php echo $penalty ?></p>
When I try to run it, there is an error Undefined variable: penalty
.
I am pretty sure that my validation codes are correct
How could I pass the penalty variable to the page itself.
I think it would resolve the error.
The problem is that the $penalty
is only set after you submit the form. You should be able to fix this by simply moving the penalty paragraph inside your elseif/else blocks where a penalty should actually be shown.
...
elseif ($ret < $duedate)
{
echo "<p>Penalty: 0</p>";
else
{
$penaltydays = date_diff($duedate,$ret) ;
$diff_date = $penaltydays->format('%a');
$penalty = $diff_date * $books * 10;
echo "<p>Penalty: $penalty</p>";
}
This way it will only be displayed if it has been calculated.
Side note, I don't think this will work the way you are expecting it to because your select options do not have value attributes. You need to add them like this:
<option value="1"> 1 </option>