Jamilah Jamilah - 1 month ago 15
PHP Question

How to check time range in PHP

I want to display an error if someone enter :


  1. The same timeout/timein time

  2. Overlap timeout/timein time

  3. Is in range beetwen timeout/timein time



But it didn't work . the time still can be insert into database. Code as below :

<?php
$connect = mysqli_connect("localhost", "root", "root", "db");
global $connect;

if(isset($_POST['Submit']))
{
$timeout = '08:30:00';
$timein = '12:30:00';
$time_out_user = $_POST['timeout'];
$time_in_user = $_POST['timein'];

if(($time_out_user >= $timeout) && ($time_out_user <= $timein))
{
echo "Duplicate time";
}
else
{
$add = "INSERT INTO table (timeout,timein)
VALUES ('$time_out_user','$time_in_user')";
$addDateTime = mysqli_query($connect,$add);
echo "Time added";
}
}
?>
<form action="time.php" method="post">
<table>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time Out: </td>
<td><input type ="time" name="timeout" size="30"></td>
</tr>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time In: </td>
<td><input type ="time" name="timein" size="30"></td>
</tr>
</table>

<p><input class="btnSuccess" type ="submit" name="Submit" value="Submit"> </p>
</form>


Appreciate if someone can help me to solve this problem . Thanks.

Answer

Work with timestamt use strtotime to convert date to time stamp:

$timeout        = strtotime('08:30:00');
$timein         = strtotime('12:30:00');
$time_out_user  = strtotime($_POST['timeout']);
$time_in_user   = strtotime($_POST['timein']);