Adam
Adam

Reputation: 29029

How to handle unique username in php form

I have a register form that goes through the following steps:

  1. Fill in user information (name,adress,etc.) and username
  2. If user presses the submit button, it is checked if username is already in the database or not
  3. If username is already in use, he must rename username, if not, it is shown what he has entered (name,adress etc.).
  4. He has to confirm the website rules and that his input data is correct. If he presses the confirm button, a row with his details and username will be inserted in the database.

I do not want to insert the row in the database after step 2., because I dont want rows from users in my database that did not confirm the rules. Also I want to keep step 3., so the user can make sure that his data is correct. Unfortunately, at the moment the code cant prevent the unlikely case that two user register at the same time with the same username. How does one prevent this case in general? I know there are a lots of php forms out there who proceed with these 4 steps.

EDIT: Sorry, that I didn't make it clear enough: I am not concerned about double entries in my database, this can be prevented by setting the username field unique. I want to know how can I check in step 2. that the username is not used in the database AND not used by any other user who is currently using the registration form.

Upvotes: 0

Views: 750

Answers (2)

Alejandro Urbano Alvarez
Alejandro Urbano Alvarez

Reputation: 3346

Data integrity in a database should be ensured by the database, not by the interface. This means that if you want UNIQUE usernames you should use the built in UNIQUE index in the database.

That way it is impossible to have two users with the same name, even if they registered at the same time.

UPDATE:

Based on your last edit I would could create a temporary table where you would insert the username in Step 2, supposing it doesn't exist in your users table. That way a user can "lock" a username until they complete registration in Step 4.

Once they reach Step 4 you move the data from the temporary table to the users table.

Upvotes: 3

Ashish Sajwan
Ashish Sajwan

Reputation: 704

so here is what you can do but make sure what @chevi said .. alter your table and add unique attribute that username column... that all at backend..

now comes front end ..in the form when user has chosen/entered username you can make a ajax call which checks user entered username in your DB and returns TRUE Or FALSE accordingly you can then n there notify user that hey this user name is already taken also you can restrict user to submit that form

Upvotes: 0

Related Questions