如果用户已经预订了同一酒店,则向用户显示该消息

时间:2017-04-12 20:46:55

标签: php mysql

我有一个酒店预订系统,允许用户预订他们选择的酒店。但是,如果他们已经预订了同一家酒店,我想为用户显示一条消息。

这是我尝试使用但不起作用的代码。每次运行代码时,它似乎总是显示代码而不放置按钮(即使用户没有预订酒店)。

$hotel_id = $id;

//check if username exists
$sql = "SELECT COUNT(id) FROM book WHERE hotel_id = 
    '".$hotel_id."' AND username = '".$_SESSION['user_name']."' ";

$thisresult = mysqli_query($con,$sql);

if(mysqli_num_rows($thisresult)>=1){
        echo "You have already booked this hotel";
} else {
    echo "<button style='margin-left: -420px; margin-top: 220px;' type='submit'> <a href='booknow.php?id=".$id."'> Book now!</a></button>"; 
}

我在mysql中使用的表;

Table name: Book
id(int 11),
username(varchar 30), 
hotel_id(int 11),
phone(varchar 50),
date(),
num_nights(int 60)
num_rooms(int 4)

2 个答案:

答案 0 :(得分:0)

您的计数查询始终返回一行。

尝试将此查询用于您的代码

$sql = "SELECT id FROM book WHERE hotel_id = '".$hotel_id."' AND username = '".$_SESSION['user_name']."'";

答案 1 :(得分:0)

首先,将$_SESSION['user_name']存储在变量中:

$user_name = $_SESSION['user_name']

准备并绑定您的select语句:

$sql = $con->prepare("SELECT COUNT(id) AS id FROM book WHERE hotel_id = ? AND username = ?");

$sql->bind_param("is", $hotel_id, $user_name); // Pass your variables as parameters, the "is" denotes that your parameters are of type integer and string

$thisresult = $sql->execute(); // Execute your prepared statement

获取COUNT列的id并检查其是否大于1:

while($row = mysqli_fetch_array($thisresult)) {
    $id = $row['id'];
}
if ($id >= 1) {
    echo "You have already booked this hotel";
} else {
    echo "<button style='margin-left: -420px; margin-top: 220px;' type='submit'> <a href='booknow.php?id=".$id."'> Book now!</a></button>";
}