Grace Michelle Grace Michelle - 6 months ago 15
PHP Question

PHP - Check Date Range

I have a table on database called

period
. The fields in this table are:
code | name | status | open_date | close_date
. The date format is
Y/m/d
.

This is what I want: if today's date is out of date range in the database, the site won't display a form and a table column.

This is my code:

<?php
$sql5 = "select close_date from period"
. " where status='1'";
$result5 = mysqli_query($link, $sql5);
if (!$result5) {
die("<h3>SQL Error</h3>" . $sql5);
}
$row5 = mysqli_fetch_array($result5);

$date = date("Y/m/d");
?>

<?php
if($date >= $row3['open_date'] && $date <= $row5['close_date']) {
?>
<form action="manageInputPerwalian.php" method="POST">
<table align="center">
<tr>
<td>MK Code:</td>
<td><input type="text" name="mkCode"/></td>
</tr>
<tr>
<td>KP:</td>
<td><input type="text" name="kp"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="SUBMIT"/></td>
</tr>
</table>
</form>
<?php } ?>


<table border="1" style="width:100%">
<tr>
<th>MK CODE</th>
<th>MK NAME</th>
<th>CLASS</th>
<?php if($date >= $row3['open_date'] && $date <= $row5['close_date']) { ?>
<th>CANCEL</th>
<?php } ?>
</tr>
</table>


But, either today's date is out of range or in the range, the form and the table column won't show up. What's wrong? Please explain your answer. Thanks

Answer

use strtotime() to convert the dates to timestamp and compare, as,

$openDateStr = strtotime($row3['open_date']);
$closeDateStr = strtotime($row5['close_date']);
$todayStr = strtotime(date("Y/m/d"));
//compare
if($todayStr >= $openDateStr && $todayStr <= $closeDateStr) {
..
Comments