MySQL / PHP: catch all entries between 2 times and check against 2 other times

人盡茶涼 提交于 2020-01-15 09:54:07

问题


I have a database where people can book rooms within two certain times, but there may be other people searching for an available room within the same times - or partly in the same time.

Database looks like this:

order | room | user | date (date-format) | from (time) | to (time)
1       123    foo    2013-04-04           12:00:00       17:00:00

The problem comes when another user searches if the room is available from f.ex 13:00 to 18:00, since I only manage to search if the room is available in the exact same time.

The query has to search on specific room at a specific date, and a time aswell. If the room is busy in all, or some of the hours, I'd like to catch this and say to the user that the room is busy.

Any tips? If it's easier to manage through PHP I'd be glad too :-)


回答1:


Why not solve it using SQL like this (untested):

SELECT *
FROM booked
WHERE
    room=$room AND
    date=$date AND
    (
        (
            /*
            The reservation starts in the requested period
            */    
            from <= $start_time AND
            to > $start_time
        ) OR (
            /*
            The reservation ends in the requested period
            */
            from < $end_time AND
            to >= $end_time
        )
    );     

This query will return all reservations between $start_time and $end_time and allows reservations back to back. If you don't want to allow reservations back to back change the < and > to <= and =>.

Important: Make sure to not just use string interpolation and insert user-supplied input unescaped as it will leave your application vulnerable to SQL-injection attacks.




回答2:


An improvement on the answer by @Delphinator

SELECT *
FROM booked
WHERE
    room=$room AND
    date=$date AND
    (
       TIME("$start_time") BETWEEN from and to 
       OR
       TIME("$end_time") BETWEEN from and to
    );

BETWEEN does exactly what you would think.



来源:https://stackoverflow.com/questions/15807516/mysql-php-catch-all-entries-between-2-times-and-check-against-2-other-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!