从ID不在另一个查询中的房间中选择ID +(日期比较)

时间:2017-05-29 17:01:51

标签: php mysql

我有两张桌子,房间和预订。

Rooms
id        description        beds        price
1         blah blah          2           100
2         blah blah          3           100
3         blah blah          4           100
4         blah blah          2           100

Reservations
id        room_id        checkin        checkout            paid
1         1              5-5-2017       7-5-2017            1
2         2              5-5-2017       9-5-2017            1
3         2              10-5-2017      12-5-2017           0
4         3              2-5-2017       4-5-2017            1

我的PHP代码

user inputs $checkin, $checkout (dates) and $adults, $children
$sql = "SELECT id FROM rooms WHERE beds >= ($adults + $children) AND id NOT IN (SELECT room_id FROM reservations WHERE ($checkin BETWEEN checkin AND checkout) AND room_id IS NOT NULL) ";    

结果是整个表格中包含我输入的任何日期。

任何人都知道出了什么问题?

样品

User input

Checkin : 6-5-2017
Checkout : 8-5-2017
Adults : 1
Children : 0

我应该得到身份3和4的空间

<?php
    require('connect.php');
    $checkin = $_POST['checkin'];
    $checkout = $_POST['checkout'];
    $adults = $_POST['adults'];
    $children = $_POST['children'];
    $valid = $_POST['cameFromRegisterPage'];

    if(!isset($valid) || $valid != 'true'){
        header("location: ./books.php"); 
    }

    $sql = "SELECT id FROM rooms WHERE beds >= ($adults + $children) AND id NOT IN (SELECT room_id FROM reservations WHERE ($checkin BETWEEN checkin AND checkout) AND room_id IS NOT NULL) ";
    $result = $con->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<div style='width:90%;background-color:#ffffff; padding:15px; text-align:left; margin-top:5px; margin-bottom:5px; opacity:0.9;'>";
            echo "<p>Description : " .$row["description"]. " &emsp; | &ensp; Beds : " .$row["beds"]. " &emsp; | &ensp; Price per night : " .$row["ppn"]. "€ &emsp; | &ensp; <a href='./rooms/room".$row['id'].".php' style='float:right;'>Book now</a></p>";
            echo "</div>";

        }
    } 
    else {
        echo "0 results";
        //header("location: ./books.php");
    }
    $con->close();
?>

1 个答案:

答案 0 :(得分:1)

room_id仅在预订表中,您不应在NOT INT之外进行过滤。

$sql = "SELECT id 
         FROM rooms 
          WHERE beds >= ($adults + $children) 
            AND id NOT IN (SELECT room_id FROM reservations WHERE ('{$checkin}' >= checkin AND '{$checkin}' <= checkout) AND room_id is not null) ";
PS:我已经开始使用酒店的软件,只是关于业务规则,将成人与数据库中的儿童床分开是很重要的,将来您的系统可能会遇到一些麻烦。