Ryan
Ryan

Reputation: 6057

How to properly check if username is taken?

I'm using PHP/MySQL. What is the best way to check if the username is already taken?

Right now all I do is execute a select statement to see if the username is already taken. If the select returns a row then I stop and display an error message. If the select doesn't return anything then I insert the new user.

But is there a more efficient way? For example can I use UNIQUE on the username column and then only execute an insert statement(and get an error from the insert if it's already taken).

Upvotes: 3

Views: 998

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562921

You do have the risk that some other thread will insert your user name in the brief moment between your SELECT confirming that the user doesn't exist and the INSERT where you insert it. This is called a race condition.

It may seem like the chance of that happening is slight, but there's a saying about that: "One in a million is next Tuesday."

Yes, a UNIQUE constraint on the username can prevent you from INSERTing a duplicate username. Declare that constraint.

Some articles will tell you that once you have a UNIQUE constraint, you don't have to do the SELECT anymore. Just try the INSERT and if it conflicts, then report the error.

However, I helped a site recover from a problem caused by this technique. On their site, users were attempting to create new usernames very quickly, and resulting in a lot of conflicts on the INSERT. The problem was that MySQL increments the auto-increment primary key for the table, even if the INSERT was canceled. And these auto-increment values are never reused. So the result was that they were losing 1000-1500 id numbers for every INSERT that succeeded. They called me when their INT primary key reached 231-1 and they couldn't create another row in the table!

The solution they used was first to try the SELECT, and report a duplicate. Then if it seemed safe, try the INSERT -- but write the code to handle the possible conflict with the UNIQUE constraint anyway, because the race condition can still occur.

Upvotes: 5

Related Questions