How to keep the uniqueness of the concurrent write database?

Source: Internet
Author: User
A, B two requests concurrent  registration of the same user name username= ' myname ' $is _user = "Select username from users WHERE username= ' myname '"; if (! $is _user) {echo ("INSERT into users (username) VALUES (' myname ')");}


If the field in the table does not have a unique index set, how does the program control uniqueness?
A, B query the table, the results can be registered, so all executed the INSERT, but the user name is the same, so that the data is not unique. Would that be so, how to avoid it?


Reply to discussion (solution)

Database lock operation

Database lock operation
Read the lock seems to be shared ah, everyone can read at the same time, so there are incorrect results.

Why not add a unique key?

The simplest method of database plus unique key

A little more complicated:
Single Web machine, using local file lock flock, a user name a local file
Multiple machines, using Memcache Inc to implement the locking mechanism http://ju.outofmemory.cn/entry/48924

I understand, thank you all.

I also just occasionally think, if not the only index, what method to solve the problem.

The simplest method of database plus unique key

A little more complicated:
Single Web machine, using local file lock flock, a user name a local file
Multiple machines, using Memcache Inc to implement the locking mechanism http://ju.outofmemory.cn/entry/48924
Please ask Memcache again.

$v = $memcache->get ($key);
if ($v = = = False) {
$memcache->set ($key, 0);
}
$index = $memcache->increment ($key, 1);

Two concurrent requests A/b will get ($key) at the same time
Then a set ($key), then B set ($key) is not covered by the latter

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.