Check if username already exists in database MySQL

2019-01-20 06:21发布

I have a registration.php page I made and I need to check if a username is already in my database so that I won't have 2 members with the same name...

Here is how I am inserting the user info into the database (username, password, date of registration, etc.):

mysql_query("INSERT INTO UserDb (ID, TimeStamp, UserName, Password) VALUES ('$ipaddress', NOW(), '$user_username', '$user_password')");

How can I check that database "UserDb" under the "UserName" field to make sure the user's variable "$user_username" doesn't already exist?

4条回答
Root(大扎)
2楼-- · 2019-01-20 06:25

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.

查看更多
迷人小祖宗
3楼-- · 2019-01-20 06:33

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.

查看更多
Melony?
4楼-- · 2019-01-20 06:42

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';

查看更多
甜甜的少女心
5楼-- · 2019-01-20 06:48

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

查看更多
登录 后发表回答