日期时间可用性在PHP中显示错误结果

时间:2019-07-11 07:07:55

标签: php codeigniter datetime

我有一家商店开闭时间,我想展示两件事 1)每30分钟创建一个时隙 2)并与数据库匹配,是否预定或可用时隙

这是我的数据库

表名- usr_bookng

id      shop_id     date                start_time      end_time
1       4           11-07-2019          10:00:00        11:30:00

我尝试使用以下代码,它可以正确创建时隙,但显示时隙状态错误,可以显示以下消息

结果

Array
(
    [1] => Array
        (
            [start] => 10:00
            [end] => 10:30
            [status] => availiable
        )

    [2] => Array
        (
            [start] => 10:30
            [end] => 11:00
            [status] => availiable
        )

    [3] => Array
        (
            [start] => 11:00
            [end] => 11:30
            [status] => booked
        )
}

问题是这样的,只有第三个时段显示已预订,所有三个时段都应该预订,我的错在哪里 这是我的代码

$duration="30";
        $start="10:00AM";
        $end="07:00PM";
        $start = new DateTime($start);
        $end = new DateTime($end);
        $start_time = $start->format('H:i');
        $end_time = $end->format('H:i');
        $i=0;

        while(strtotime($start_time) <= strtotime($end_time)){
    $start = $start_time;
    $end = date('H:i',strtotime('+'.$duration.' minutes',strtotime($start_time)));
    $start_time = date('H:i',strtotime('+'.$duration.' minutes',strtotime($start_time)));
    $i++;
    if(strtotime($start_time) <= strtotime($end_time)){
        $time[$i]['start'] = $start;
        $time[$i]['end'] = $end;
    }

    $todayDate = date('d-m-Y');
    if(strtotime($start_time) <= strtotime($end_time)){
        $time[$i]['start'] = $start;
        $time[$i]['end'] = $end;
        }

        $query=$this->db->query("select `id` from `usr_booking` where date = '$todayDate' and 
        (( `start_time` >= '$start' AND `start_time` <= '$start' ) || 
        (`end_time` >= '$end' AND `end_time` <= '$end'))");

        if ( $query->num_rows() > 0 )
            {
                $rows = $query->result_array();
                $time[$i]['status'] = 'booked';
            }
        else
        {
                    $rows = $query->result_array();
                    $time[$i]['status'] = 'availiable';
        }

1 个答案:

答案 0 :(得分:0)

我认为您的列是字符串。您应该将列更改为“ TIME”,然后将时间查询为“ TIME”。

运行一次,或者,您可以将start_timeend_time列从phpMyAdmin更改为TIME

 ALTER TABLE usr_bookng MODIFY start_time TIME ;
 ALTER TABLE usr_bookng MODIFY end_time TIME ;

根据您的查询;

 $query=$this->db->query("select `id` from `usr_booking` where date = '$todayDate' and 
 (( `start_time` >= CAST('$start' AS TIME) AND `start_time` <= CAST('$start' AS TIME) ) || 
 (`end_time` >= CAST('$end' AS TIME) AND `end_time` <= CAST('$end' AS TIME) ))");

但我也认为您的查询中存在逻辑错误,请解决此问题,最终查询应为:

$query=$this->db->query("SELECT `id`  FROM `usr_booking` WHERE date = '$todayDate'  AND
( `start_time` <= CAST('$start' AS TIME)  AND `end_time` >= CAST('$end' AS TIME) )");