如果数据库中不存在用户的电子邮件,则发出警报并阻止数据保存到数据库中

时间:2019-09-04 04:02:18

标签: php sql pdo

我创建了一个用于大学预订房间的页面。当工作人员想要预订房间时,他/她需要去柜台并要求管理员/ PIC预订房间。管理员需要完整填写所有详细信息,包括人员(请求者)电子邮件,目的,开始时间和结束时间。目前,如果时间与其他事件发生冲突,则无法进行预订。

当我输入错误的员工电子邮件(数据库中不存在该电子邮件)并提交表单时,它将给出此错误

“ INSERT语句与FOREIGN KEY约束“ FK__Booking__Request__619B8048”发生冲突。该冲突发生在数据库“ madb”的表“ dbo.Staff”的“电子邮件”列中。”

现在,当管理员在单击按钮提交后输入了错误的职员电子邮件时,我想如何提醒管理员。

下面是我的PHP代码

<?php

if(isset($_POST['Submit'])) { 
    $Requested_by = $_POST['Requested_by'];
    $date = $_POST['date'];
    $timeFrom = $_POST['timeFrom'];
    $timeTo = $_POST['timeTo'];
    $Meeting_Description = $_POST['Meeting_Description'];
    $Room_ID = $_POST['Room_ID'];
    $Admin_email = $_POST['Admin_email'];
    $Remark = $_POST['Remark'];
    $Book_Status = $_POST['Book_Status'];
    $StartTime = $date." ".$timeFrom;
    $EndTime = $date." ".$timeTo;

    $sql2 = "SELECT * FROM booking WHERE NOT (StartTime > :timeTo OR EndTime < :timeFrom)";
    $query2 = $conn->prepare($sql2);
    $query2->bindParam(':timeFrom',$StartTime,PDO::PARAM_STR);
    $query2->bindParam(':timeTo',$EndTime,PDO::PARAM_STR);
    $query2 -> execute();
    $results = $query2 -> fetchAll(PDO::FETCH_OBJ);

    if($query2->rowCount() == 0){
    //insert data to database     

        $sql = "INSERT INTO booking(Requested_by, Book_Date, StartTime, EndTime, Meeting_Description, Room_ID, Admin_email, Remark, Book_Status) 
                VALUES(:Requested_by, GETDATE(), :StartTime, :EndTime, :Meeting_Description, :Room_ID, :Admin_email, :Remark, :Book_Status)";
        $query = $conn->prepare($sql);

        $query->bindparam(':Requested_by', $Requested_by);
        $query->bindparam(':StartTime', $StartTime);
        $query->bindparam(':EndTime', $EndTime); 
        $query->bindparam(':Meeting_Description', $Meeting_Description);
        $query->bindparam(':Room_ID', $Room_ID);
        $query->bindparam(':Admin_email', $Admin_email);
        $query->bindparam(':Remark', $Remark);
        $query->bindparam(':Book_Status', $Book_Status);
        $query->execute();

        if ($query2->rowCount() > 0){

            header("Location:../dashboard/dashboard_admin.php");

        } else {

        echo "
            <script>alert('Something wrong, please try again')</script>
            <script>window.location = '../dashboard/dashboard_admin.php'</script>
        ";
        }

    } else {

        echo "
            <script>alert('The time range you are selected is conflicted with another meeting')</script>
            <script>window.location = 'manual_booking.php'</script>
        ";

    }

}


?>

1 个答案:

答案 0 :(得分:1)

外键不能在该列中具有一个值,该值也不在被引用表的主键列中。这意味着电子邮件地址必须在主表中。因此,要么删除外键,要么先在主表中进行输入,然后在预订中插入。