mysql如何防止重复的电子邮件地址 registeres?

标签: MySQL PHP
发布时间: 2015/6/11 21:47:35
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我做了一个登录/注册系统和我遇到的一个问题不允许重复的电子邮件地址注册。我希望它工作,以便数据库不会接受数据,重复的电子邮件并将太警告用户。我有点新的 PHP,所以我不能确定如何执行此操作。谢谢你。

我在 PHP

if (empty($_POST['email'])) {
    $error[] = 'Please Enter your Email ';
} else {

    if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-   ]+)+$/", $_POST['email'])) {
       //regular expression for email validation
        $Email = $_POST['email'];
    } else {
         $error[] = 'Your Email Address is invalid  ';
    }


}


if (empty($_POST['Password'])) {
    $error[] = 'Please Enter Your Password ';
} else {
    $Password = $_POST['Password'];
}


if (empty($error)) //send to Database if there's no error '

{ // If everything's OK...

    // Make sure the email address is available:
    $query_verify_email = "SELECT * FROM members  WHERE Email ='$Email'";
    $result_verify_email = mysqli_query($dbc, $query_verify_email);
    if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
        echo ' Database Error Occured ';
    }

    if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .


        // Create a unique  activation code:
        $activation = md5(uniqid(rand(), true));


        $query_insert_user = "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$username', '$Email', '$Password', '$activation')";


        $result_insert_user = mysqli_query($dbc, $query_insert_user);
        if (!$result_insert_user) {
            echo 'Query Failed ';
        }

        if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.


mysqli_close($dbc);//Close the DB Connection

 } // End of the main Submit conditional.

?>

HTML

<form action="./index.php#openModal2" method="post" class="registration_form">
  <fieldset>
<legend>Registration Form </legend>

<p>Create A new Account</p>

<div class="elements">
  <label for="username">Name :</label>
  <input type="text" id="username" name="username" size="25" />
</div>
<div class="elements">
  <label for="email">E-mail :</label>
  <input type="text" id="email" name="email" size="25" />
</div>
<div class="elements">
  <label for="Password">Password:</label>
  <input type="password" id="Password" name="Password" size="25" />
</div>
<div class="submit">
 <input type="hidden" name="formsubmitted" value="TRUE" />
  <input type="submit" value="Register" />
</div>

解决方法 1:

添加唯一约束在 email 表中的列 members :

ALTER TABLE members ADD UNIQUE (email);

通常情况下,你会做这当你创建的表,而不是事后修改表。

官方微信
官方QQ群
31647020