我正在尝试创建预订系统,并想检查两个日期之间是否已进行预订。但是,我的SQL总是返回false。
$reservation_date_start = date('y-m-d', strtotime($fields['reservation_date_start']));
$reservation_date_end = date('y-m-d', strtotime($fields['reservation_date_end']));
// Save data to database
$table_name = $wpdb->prefix . 'mb_bookings';
$date_exists = $wpdb->get_results("SELECT * FROM $table_name
WHERE (reservation_date_start >= $reservation_date_start AND reservation_date_start < $reservation_date_end )
OR (reservation_date_end >= $reservation_date_start AND reservation_date_end < $reservation_date_end)
AND (accommodation_id = $accommodation_id)"
);
我已经尝试过使用BETWEEN
功能,但也没有取得任何成功。
数据库中的日期是正确的(y-m-d)
Db示例:
任何帮助都会非常感激,因为我已经挣扎了好几天了......
答案 0 :(得分:0)
日期格式y-m-d
给出16-04-01。将其更改为Y-m-d
即可获得2016-04-01。查询应该可以正常工作。
如果我理解你的需要,你想检查两个时期是否重叠。我认为应该这样做(标记添加的parnetheses和撇号):
SELECT *
FROM $table_name
WHERE
(
(
STR_TO_DATE('$reservation_date_start', '%Y-%m-%d') <= reservation_date_end
AND
STR_TO_DATE('$reservation_date_end', '%Y-%m-%d') > reservation_date_start
)
OR
(
STR_TO_DATE('$reservation_date_end', '%Y-%m-%d') >= reservation_date_start
AND
STR_TO_DATE('$reservation_date_start', '%Y-%m-%d') < reservation_date_end
)
)
AND (accommodation_id = $accommodation_id)
修改强>
重叠的简化条件:
SELECT *
FROM $table_name
WHERE
STR_TO_DATE('$reservation_date_end', '%Y-%m-%d') >= reservation_date_start
AND STR_TO_DATE('$reservation_date_start', '%Y-%m-%d') <= reservation_date_end
AND accommodation_id = $accommodation_id
答案 1 :(得分:0)
$reservation_date_start = date('Y-m-d',strtotime($fields['reservation_date_start']));
$reservation_date_end = date('Y-m-d', strtotime($fields['reservation_date_end']));
答案 2 :(得分:0)
SELECT * FROM $ table_name WHERE date_filed BETWEEN reservation_date_start AND $ reservation_date_end;