how can you check if a user already exists?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
scheinarts
Forum Commoner
Posts: 52
Joined: Wed Jul 25, 2007 2:37 am

how can you check if a user already exists?

Post by scheinarts »

Hi guys,

I am creating a little self-registration app... and I need to check if the username being supplied already exists in the MySQL db.

How would I go about setting that up with php and the mysql query?

I just need something to get me going in the right path.

Thanks!
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Re: how can you check if a user already exists?

Post by JAM »

Without giving away to much, just leading you on the right path;

Get the username variable from the registrationform, and ask the database if it exists;

Code: Select all

mysql_query("select username from table where username = '$_POST[username]}'");
If mysql_num_rows() > 0 then you allready have one use by that name. If so, display error. If not, continue.

Enough? :D
scheinarts
Forum Commoner
Posts: 52
Joined: Wed Jul 25, 2007 2:37 am

Re: how can you check if a user already exists?

Post by scheinarts »

I guess :)

So can you simply say

Code: Select all

if(mysql_num_rows() > 0){ // handle error} else { //add new user }
Is that simple or is there something else to it?

Thanks
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: how can you check if a user already exists?

Post by Kieran Huggins »

That's about it, except you'll want to escape your input and pass the result of the query to MySQL_num_rows()

Code: Select all

$result = mysql_query("SELECT * FROM table WHERE username = '".MySQL_real_escape_string($_POST['username'])."'");
 
if(mysql_num_rows($result) > 0){ /* user exists */ } else { /* add new user */ }
Post Reply