How to check for duplicate entry in DB?
I've built a form on a site which captures a few fields including 'email' and posts it to a DB that I have with a table named 'data.' I'm using the jQuery Validate plugin to make sure all fields are complete, though I can't have duplicate email addresses in the db.
The plugin came with a script named emails.php which it calls when verifying the field data and here's the code:开发者_如何学JAVA
<?php
$request = trim(strtolower($_REQUEST['email']));
$emails = array('steam@valve.com', 'bill@gates.com', 'blocked@email.com');
$valid = 'true';
foreach($emails as $email) {
if( strtolower($email) == $request )
$valid = '"Thats already taken."';
}
echo $valid;
?>
This snippet is only checking the emails that are listed. Is there a way to query the DB to search through the table 'data' and check the 'emails' to see if there's a duplicate and hopefully post an error message if it is?
Also, the script does seem to work when I use any of the example emails so it is essentially 'working' I just need to tweak it to check the DB.
Put a uniqueness constraint on the email column.
Do not use a flawed "SELECT before INSERT" approach. There will always be a race condition between your "SELECT" and a subsequent "INSERT" unless you're in a global transaction, which I doubt is the case here.
You should put a UNIQUE constraint on the email column and then simply attempt to INSERT the new record and catch the uniqueness SQL error. You can catch the error by checking the error code, for MySQL for example it is 1062 or 23000 depending on the driver.
First, put a UNIQUE
constraint on the email column. Then, at sign up, run the following query:
SELECT COUNT(*) as 'count' FROM `data` WHERE email = 'requested@email.com';
You would just need to write a query to check if the email is in the table:
$query = SELECT count(*) AS `total` FROM `data` WHERE `email` = '{$request}'
$row = mysql_fetch_assoc(mysql_query($query));
if($row['total']) echo false; //exists
else echo true; //doesn't exist
edit meant to 'echo' and not 'return'
You could do maybe a php code that checks the DB for existing values using the mysql_num_rows command.
Something like this:
$result = mysql_query("SELECT email from accounts where email = $email_to_check");
$found = mysql_num_rows($result);
if ($found > 0) { echo "Email already exists"; }
else .....
精彩评论