Jamilah Jamilah - 9 months ago 62
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 :

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

$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";
$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">
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time Out: </td>
<td><input type ="time" name="timeout" size="30"></td>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time In: </td>
<td><input type ="time" name="timein" size="30"></td>

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

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

Answer Source

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']);