tags:

views:

459

answers:

4

Whats the best way to check if a username exists in a MySQL table?

A: 

Create a stored procedure to do it. Its faster than running the SQL via your code. I cannot anything more than just comparing it with the saved data in your table. ;-)

Shoban
+5  A: 
SELECT COUNT(*) as count FROM users WHERE username='whatever'

read out the first result row - if the 'count' column is > 0 then the username exists.

Alternatively, in php, you could use:

SELECT * FROM users WHERE username='whatever'

Then use mysql_num_rows (or the equivalent).

Kazar
Or you can just use a select and mysql_num_rows
Peter D
For speed, change the last to :SELECT username FROM users WHERE username='whatever' LIMIT 1Just in case you don't have a unique constraint or index
Evert
+2  A: 
SELECT 1 FROM `users` WHERE `username` = 'whatever' LIMIT 1
chaos
Which one is faster? This one or the accepted solution?
despart
In a properly indexed and constrained table (unique key on username) they should be functionally identical. Mine will do better on poorly indexed or constrained tables.
chaos
+3  A: 

If you are trying to determine if a user exists in MySQL (i.e. a user name exists that can login to MySQL itself).

select user,host from mysql.user where user = 'username';

If you need to filter by host:

select user,host from mysql.user where user = 'username' and host = 'localhost';

These queries lets you see who has access to the MySQL database server and only is accessible if you are an administrator for a MySQL server.

Redbeard 0x0A