显示一个房间的预订日

时间:2016-11-10 06:53:42

标签: php mysql oop

我正在学校的房间预订系统,但我输出预订时遇到了一些麻烦。

Public function displayRoomByDay() {
    $query = DB::GetInstance()->query("SELECT B.roomid, B.period, R.roomname, B.bookingdate, B.bookingid FROM booking B INNER JOIN room R on b.roomid = r.roomid WHERE bookingdate = '2016-11-03' and b.roomid=1 ORDER BY b.period"); //Inner join 
    $count = $query->count();
    $freeCount = 0;
        for($periods=1;$periods<=6;$periods++) {
            for($x=0;$x<$count-1;$x++) {
                $outputted=false;
                $freeCount=0;
                do {                        
                    if($query->results()[$x]->period == $periods) {
                        echo $query->results()[$x]->period . '<br>';
                        $outputted=true;
                    } else {
                        echo 'FREE' . '<br>';
                        $freeCount = 1;
                    }
                } while($outputted = false and $freeCount=0);
            }
        }
}

这是我用来输出数据的功能。我的SQL查询返回两个项目,第5期预订和第1期预订(我已通过PHPMyAdmin测试过)。我试图使用嵌套for循环和do while循环来遍历一天中可用的时段(6)。从那里我循环我的sql查询返回的两个预订,这是这段代码:

for($x=0;$x<$count-1;$x++) {
    $outputted=false;
    $freeCount=0;
    do {                        
        if($query->results()[$x]->period == $periods) {
            echo $query->results()[$x]->period . '<br>';
            $outputted=true;
        } else {
            echo 'FREE' . '<br>';
            $freeCount = 1;
        }
    } while($outputted = false and $freeCount=0);
}

然而,当我运行我的页面时,我获得1免费免费免费免费,当我想获得1免费免费免费5,因为他们是预订。

1 个答案:

答案 0 :(得分:0)

您的逻辑对于此任务非常复杂。你可以简化它:

public function displayRoomByDay()
{
    $query = DB::GetInstance()->query("
        SELECT B.roomid,
               B.period,
               R.roomname,
               B.bookingdate,
               B.bookingid
        FROM booking B
        INNER JOIN room R 
           ON b.roomid = r.roomid
        WHERE bookingdate = '2016-11-03'
          AND b.roomid=1 ORDER BY b.period"); //Inner join

    $results = array_reduce($query->results(), function ($carry, $item) {
        $carry[$item->period] = $item;
        return $carry;
    }, []);

    $periods = range(1, 6);

    foreach ($periods as $period) {
        if (isset($results[$period]) {
            echo $period . '<br />';
        } else {
            echo 'FREE' . '<br />';
        }
    }
}

我认为这就是你所需要的。