Check if username already exists in database MySQL PHP

泪湿孤枕 提交于 2019-11-28 13:05:52

You can make the username field in the database a primary key or unique, which guarantees the username uniqueness in the database.

Then, if you try to insert an already existing username the mysql_query() function will fail, returning FALSE.

Besides that, you should always query the database for the existence of the username, using a simple select statement:

SELECT username FROM table WHERE username='$php_username_var';

You can make the UserName a unique field. MySQL will then refuse to insert a new record if the username already exists.

Alternatively you can run a query searching for the username. If it doesn't exists, insert it. Wrap this into a transaction so you can be sure that after you've searched for a user, an additional new one with the same name was added before you add the new one.

create a unique key on UserName and if the INSERT errors out, check the error number.

It's best to check for the username first, rather than depending on the database to tell you via error - always better to be explicit rather than have functionality implied.

Also, you may need to consider the situation where there are one or more existing records with the same username.

For example, if a user signs up for a subscription, cancels after a few months, and then signs up again later.

Sometimes it's best to re-open the account, and other times just to create a new one...In that case it might be ok to have duplicate rows with the same username, so long as only the current one is active, and the rest are for historical reporting purposes.

In fact, you might NEED the duplicate rows if the old user instances are referenced in your billing tables, notes, etc. If you deleted the user, it would cause issues with your reporting.

A word of advice as well - consider using the user's email address as their username - you know it's a string that's unique to them, gives you a default way to contact them, and can be validated at sign up.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!