Check UNIQUE element before inserting it

2

I have a table in a MySQL database where one of your fields (email) is UNIQUE , when inserting a record I must first make a select checking if there is a record whose email field match the email I want to insert (remembering that the field is UNIQUE) or should I handle the generated exception? I'm using PDO.

    
asked by anonymous 13.04.2015 / 19:09

2 answers

4

Do not do this. You are creating a race condition . You check if it is ok, then another user (or the same one in another session) changes the state of the bank, that is, a value that was unique, is no longer, then the code will insert in the certainty that it is unique and it already it is no more, and will give error. So if you check something that does not guarantee anything, do not check. Treat the exception raised, this is one of the main reasons for exceptions.

    
13.04.2015 / 19:16
3

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

I think this will solve your problem.

    
13.04.2015 / 19:21