PHP Code:
$result = mysql_query("SELECT * FROM Members WHERE email='$email'");
if (mysql_num_rows($result)==1) {
echo("<P>E-mail address already in database!");
exit();
}
I'd make
PHP Code:
if (mysql_num_rows($result)==1)
be
PHP Code:
if (mysql_num_rows($result)>0)
Why? because if, by the time you implement this scheme, your database already contains duplicate e-mails, or you add a bunch of e-mails automatically (importing data) without using the script, you can still guarantee that no more duplicates can be added.
Actually, I think this corresponds more accurately to the concept you are trying to code: you are not interested in knowing if there is exactly one entry in the table, you want to know if there's *any* entry in the table with that e-mail.
If you're writing, let's say, a subscription system, using this system you can guarantee that even if the database already contains a duplicate of my address because of some mistake, I won't be able to sign up again.
Also, if you ever intend to port your code to a database engine other than MySQL, you should check the case of the e-mail address in the search. The way I do that is to do
PHP Code:
$email=strtolower($email);
before adding the row.
I use the following code to create the table
create table members (email VARCHAR(100) NOT NULL,
-> name VARCHAR(100) NOT NULL
-> );
Like I said, I check to see if an e-mail address already exist in the database. But I want to make it impossible to add the same e-mail address even if my check fails! In other words I want to make the email field unique. How do I do this?
Create your table with something like
Code:
create table members(memberid integer auto_increment primary key,
-> email varchar(100) not null unique,
-> name varchar(100) not null
-> );
Using that, you no longer need to perform any prior check by yourself, MySQL won't let you insert a duplicate e-mail, and you will have to check the $result to see if the insert was successful or not. However, beware, because MySQL does all comparisons case insensitively, which is right for you, but other RDBMS will take case into account, so me@myhost.com will not be thought of as a duplicate of Me@MyHost.com, and you will have a problem.
Hope you find that useful.
Bookmarks