I have an events page on my website and I run a event bar at the top of my header showing the latest event. I'm trying to figure out how to write this correctly.
If the event has not happened I want to show it. If the event has already happened I do not want to show the event.
CODE:
<?php //SELECT QUERY...
foreach($events->results() as $e):
$now = "now()";
if($e->event_date <= $now){?>
<h1>Show Event</h1>
<?php }
elseif($e->event_date > $now){ ?>
<h1>DON'T Show Event</h1>
<?php
}
endforeach;
So basicly if the event's timestamp is less than or equal to the upcoming event, I want it to show.
If the event's timestamp is greater than the current date and time of the event, I do not want it to show.
now()
is mysql function . In PHP we use time() to get the current timestamp
It is used as
$now = time();// get current timestamp
Use strtotime()
to convert date in time stamp then use for comparison
$now = time();
foreach ($events->results() as $e):
if (strtotime($e->event_date) >= $now) {// check for greater then equal to
?>
<h1>Show Event</h1>
<?php
} else {
echo "<h1>DON'T Show Event</h1>";
}
endforeach;
You are in right Direction, change it like
<?php //SELECT QUERY...
foreach($events->results() as $e):
$now = date("Y-m-d H:i:s");
if(date("Y-m-d H:i:s", strtotime($e->event_date)) >= $now){
echo "<h1>Show Event</h1>";
}else{
echo "<h1>DON'T Show Event</h1>";
}
endforeach;
?>