插入使用php后如何更新房间状态

时间:2017-12-26 05:09:55

标签: php html mysql

我有两张桌子是tblroom和tblrent。如何在插入表租后更新表空间的状态字段。插入工作正常但更新无效。这是我的代码。

if($_POST) {    

    $validator = array('success' => false, 'messages' => array());
    $cusName = $_POST['cusName'];
    $room_num = $_POST['room_num'];
    $strDate = $_POST['strDate'];
    $book = $_POST['book'];
    $fctStatus = $_POST['fctStatus'];

    //insert values to database
    $sql = "INSERT INTO tblrent (name, room, start_date, booking, status) 
    VALUES ('$cusName', '$room_num', '$strDate', '$book', '$fctStatus')";
    $query = $connect->query($sql);

    //update the room status
    $update = "UPDATE tblrooms SET status ='$fctStatus' WHERE rNumber=$room_num";
    $query2 = $connect->query($update);

        if($query === TRUE) {           
            $validator['success'] = true;
            $validator['messages'] = "Successfully Added";      
        } else {        
            $validator['success'] = false;
            $validator['messages'] = "Error while adding the Customer information";
        }
    // close the database connection
    $connect->close();
    echo json_encode($validator);
}

1 个答案:

答案 0 :(得分:0)

首先,您应该尝试显示导致问题的错误消息。 $room_num整数也是?如果它不是,那么您可能希望将其包装在更新语句中的引号中。 $update = "UPDATE tblrooms SET status ='$fctStatus' WHERE rNumber='$room_num'";

注意:您不应将值直接从输入传递到查询中,因为可能会输入恶意输入,您可能会成为SQL Injection的受害者。在将输入传递给查询之前,请考虑使用prepared statements (PDO)或正确过滤和准备输入。

if($_POST) {    

$validator = array('success' => false, 'messages' => array());
$cusName = $_POST['cusName'];
$room_num = $_POST['room_num'];
$strDate = $_POST['strDate'];
$book = $_POST['book'];
$fctStatus = $_POST['fctStatus'];

//insert values to database
$sql = "INSERT INTO tblrent (name, room, start_date, booking, status) 
VALUES ('$cusName', '$room_num', '$strDate', '$book', '$fctStatus')";
$query = $connect->query($sql);

//update the room status
//Note the quotes around the $room_num which should be used if it isn't an integer
$update = "UPDATE tblrooms SET status ='$fctStatus' WHERE rNumber='$room_num'";
$query2 = $connect->query($update);
    //check if the insert query worked
if($query === TRUE) {           
    $validator['success'] = true;
    $validator['messages'] = "Successfully Added";      
} else {        
    $validator['success'] = false;
    $validator['messages'] = "Error while adding the Customer information" . $connnect->error;
}
    //check if the update query worked
if ($query2 === TRUE) {
    echo "Room status updated successfully";
} else {
    echo "Error updating room status: " . $connnect->error;
}

// close the database connection
$connect->close();
echo json_encode($validator);
}