我正在尝试对我在数据库中的日期/时间字段使用dateTime函数来检查彼此是否大于或小于彼此。
我遇到的问题是,如果我将条件设置为if ($date >= $end_date)
,那么我只会输出$noEvents
,即使有end_date
个字段实际上更大比$date
(当前日期时间)。如果我将条件更改为if ($date <= $end_date)
,则会发生同样的情况,反之亦然。
似乎这个if语句只读取一次而不是循环遍历每条记录。
以下是我的数据库中的内容。前两个记录的日期大于今天。第三条记录的日期少于或等于今天。
如果条件是:if ($date >= $end_date)
我只获得$noEvents
。
如果条件是:if ($date <= $end_date)
我显示了所有三个数据库记录,即使标题为“Test”的记录不应显示。
有谁知道为什么这不能正常工作?
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();
}
更新 - 无事件代码
if ($event_stmt = $con->prepare($sql_events)) {
$event_stmt->execute();
$event_rows = $event_stmt->fetchAll(PDO::FETCH_ASSOC);
$noEvents = NULL;
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'];
$end_date = new DateTime($event_row['end_date']);
$date = new DateTime('now');
//$active_events = count($event_name);
//var_dump($active_events);
//if ($active_events === 0) {
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 ($noEvents) {
echo $noEvents;
}
答案 0 :(得分:1)
所以这是相关的代码
$end_date = $event_row['end_date'];
$date = new DateTime("now");
if ($date <= $end_date) { }
问题在于您将字符串与DateTime
对象进行比较。你应该做的是让$end_date
成为DateTime
,你的测试应该按照书面形式工作
$end_date = new DateTime($event_row['end_date']);