Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to be able to prevent duplicate SQL text field rows. That is, if row 1 has the name field already defined as "John Smith", I don't want it to be able to add another "John Smith" (as common as that name might be).

I tried checking if it existed at time of insertion, but the problem is, if you open up two browser windows at the same time and click submit simultaneously, they'll both check, the check will clear, and then they'll both insert if it's close enough together.

Oh, and this is on a PHP site.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
290 views
Welcome To Ask or Share your Answers For Others

1 Answer

CREATE UNIQUE INDEX idxname ON tablename (fieldname);

Adding this index will ensure that no duplicate entries for fieldname field will be recorded into tablename table.

You will get a MySQL error with the second client. You should handle this in your PHP code, and put up the form again (instead of just displaying the error message).

An other possibility (for more complex sitations) is the LOCK functionality. If you lock the table before checking and then you insert your record a concurrent operation (in the second browser window) will be delayed until you release the locks. Then the record will be already saved, so the second PHP script will see it and handle the sitation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...