Check UNIQUE element before inserting it

Asked

Viewed 170 times

2

I have a table in a Mysql database where one of your fields (email) is UNIQUE, when entering a record I must first perform a select checking if there is a record whose email field matches the email I want to enter (remembering that the field is UNIQUE) or should I treat the generated exception? I am using PDO.

2 answers

5


Don’t do that. You’re creating a race condition. You check if it is ok, another user (or the same in another session) changes the state of the bank, ie, a value that was unique, is no longer, then the code will enter in the certainty that it is unique and it is no longer, and will give error. So if you’re gonna check something that doesn’t guarantee anything, don’t check it. Deal with the generated exception, this is one of the main reasons for exceptions (or error codes).

3

Ricardo, if you want to do the insertion without doing any kind of validation... type the email is already registered but the data are different or the email is already registered I have to warn the user, Voce can use INSERT IGNORE that will try to insert but if the email is already registered it will ignore the insertion. But for this to happen your EMAIL field has to be UNIQUE.

I think this will solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.