I am attempting to use the dateTime function against a date/time field I have in my database to check against each other as to whether it is greater than or less than each other.
The issue I am running into is that if I set the condition to if ($date >= $end_date)
, then I only get the $noEvents
to output, even though there are end_date
fields that are actually greater than the $date
(current dateTime). Then the same happens if I change the condition to if ($date <= $end_date)
, except vise versa.
It seems as if this if statement is only reading once and not looping through each record.
Here is what is in my database. The first two records have dates greater than today. The third record has a day less than or previous of today.
If the condition is : if ($date >= $end_date)
I only get $noEvents
.
If the condition is: if ($date <= $end_date)
I get all of the three database records displaying, even though the record titled "Test" should not be displaying.
Does anyone know why this isn't working correctly?
if ($date <= $end_date) {
$noEvents = 'No events are scheduled yet.';
} else {
events CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event_name` text NOT NULL,
`display_date` varchar(100) NOT NULL,
`description` text NOT NULL,
`event_img` text NOT NULL,
`end_date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
try {
$con = new PDO('mysql:host='.$servername.';dbname=name', $username, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_events = "
SELECT *
FROM events
ORDER BY end_date ASC
LIMIT 3
";
if ($event_stmt = $con->prepare($sql_events)) {
$event_stmt->execute();
$event_rows = $event_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($event_rows as $event_row) {
$event_name = $event_row['event_name'];
$display_date = $event_row['display_date'];
$event_description = $event_row['description'];
$end_date = $event_row['end_date'];
$date = new DateTime("now");
if ($date <= $end_date) {
$noEvents = 'No events are scheduled yet.';
} else {
echo '<div class="eventBlock">';
echo '<span class="hGc">'. $display_date .'</span>';
echo '<a href="#" class="hLink">'. $event_name .'</a>';
echo '<p class="dG margBot40">'. $event_description .'</p>';
echo '</div>';
}
}
if (isset($noEvents)) {
echo $noEvents;
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Aucun commentaire:
Enregistrer un commentaire