Code
Code

Reputation: 6251

How to prevent MySQL race condition duplicate entry in transaction

My PHP/MySQL code to INSERT a user account is something like:

  1. Start transaction
  2. Perform a SELECT to ensure Username (UNIQUE) does not already exist
  3. INSERT user account with Username and Password
  4. Other MySQL queries
  5. Commit transaction

My understanding it that, when multiple scripts are being run to insert user accounts with the same username, they may encounter a race condition and try to insert the same username. How can I prevent this?

Upvotes: 2

Views: 358

Answers (1)

Stefan Schmidt
Stefan Schmidt

Reputation: 1152

You could make the column 'username' unique. That way, one of those commits will fail since it would violate that constraint.

Upvotes: 1

Related Questions