简体   繁体   中英

PHP check if email already exist

Im trying to check if email already exist in my DB (in my registration form), but I want in the same IF statement to check if its email actually.

I wrote this code, but I still can register with email address that already exist in the DB. What am I doing wrong?

function CheckEmail()
{
     $email = $_POST['email'];
     $query = mysql_query("SELECT email FROM users WHERE email='" . $email . "'");
     $a = mysql_num_rows($query);
     if ((!filter_var($email, FILTER_VALIDATE_EMAIL)) OR ($a >= 1))
     {
         echo "Your email is not valid or already exists!";
         echo $a;
     }
     else
     {
         return true;      
     }
}

You should use a UNIQUE constraint on your email column, this way you'll get a MySQL error when you try to insert a duplicated value - an email that is already there.

You simply have to check the results of your query, if you don't have any errors then it was inserted, if you get this error, the email is already in use.

If I recall correctly, the error number is 1062 for a duplicate entry.

By doing this, you're avoiding an extra SELECT query.

Checking whether an email address is valid is incredibly complex; search stackoverflow for "verify email address" to get a feeling.

Thus, I don't think checking it with the same if clause is a good idea at all -- it even reduces the helpfulness of your error message by leaving your user in doubt about whether the email address is invalid or already there.

You can do this by using while loop and checking if the database has email entered or not.

following code.

function CheckEmail()
{
     $email = $_POST['email'];
     $query = @mysql_query("SELECT email FROM users WHERE email='" . $email . "'");
     $a = mysql_num_rows($query);
     while($row = mysql_fetch_array($query)){
        if($row['email'] == $email){
            echo "Email you entered is already registered";
        }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM