如何在PHP中限制用户多次填写应用程序

时间:2017-05-04 16:57:18

标签: php

我有这个PHP应用程序,用户学生可以查看并申请其他用户雇主可以发布的实习。 Screenshot of the Student Dashboard。问题是:

如果学生已申请实习,则应限制他再次申请。 This is the form when Apply is clicked

这是表单页面的PHP代码:

`

$name=$_POST['name'];
$email=$_POST['email'];
$employer=$_POST['employer'];
$title=$_POST['title'];

$query="INSERT INTO student_applications(name,email,employer,job_title) VALUES('$name','$email','$employer','$title')";
$result=mysqli_query($conn,$query);
if($result)
    header("Location: student-profile.php");
else
    header("Location: register_intern.php");

>`

2 个答案:

答案 0 :(得分:0)

您可以在student_applications表中查找记录,看看该学生是否已经申请。

// $email is assumed to be properly escaped for your queries, otherwise it will be sql-injection vulnerable.
$query = "select id from student_applications where email = '" . $email . "'";
$verification_result = mysqli_query($conn,$query);
if(mysqli_num_rows($verification_result) == 0){
    // the user didnt apply yet, insert the application
    $query = "INSERT INTO student_applications(name,email,employer,job_title) VALUES('$name','$email','$employer','$title')";
    $result = mysqli_query($conn,$query);
    if($result)
        header("Location: student-profile.php");
    else
        header("Location: register_intern.php");
}else{
    // the user already applied
    // show error
}

答案 1 :(得分:0)

student_applications.email上创建唯一约束。那么每个申请人就不可能有一行以上:

CREATE UNIQUE INDEX email ON student_applications (email);

然后,当需要插入新用户时,不要费心检查是否存在,只是尝试插入新行。如果已经有一行使用相同的电子邮件,则插入将失败。