Page 1 of 1

how can you check if a user already exists?

Posted: Thu Jan 24, 2008 1:00 pm
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!

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

Posted: Thu Jan 24, 2008 1:12 pm
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

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

Posted: Thu Jan 24, 2008 1:27 pm
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

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

Posted: Thu Jan 24, 2008 1:57 pm
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 */ }