views:

48

answers:

1

Hi,

I've got a signup/login system on my site, and I've made it so that if someone tries to sign up with a username that is already in use, it posts an error underneath the form. However, instead of posting the error message that I created, it returns a MySQL error "Error: Query was empty". Here is the code that I am trying to use to do this:

 // checks if the username is in use
  if (!get_magic_quotes_gpc()) {
   $_POST['username'] = addslashes($_POST['username']);
  }
 $usercheck = $_POST['username'];
 $check = mysql_query("SELECT username FROM userpass WHERE username = '$usercheck'") 
 or die(mysql_error());
 $check2 = mysql_num_rows($check);

 //if the name exists it gives an error
 if ($check2 != 0) {
   $error = "Sorry, the username ".$_POST['username']." is already in use.";
     }

What am I doing wrong?

Thanks

+1  A: 

Your query is nonsense (SELECT username ... WHERE username =...)

What you must do is adding UNIQUE constraint on username and trying directly to insert the user in your database. If username does already exist the query will return an error.

ALTER TABLE user ADD UNIQUE (username)

and just try to insert an user with existing id.

MatTheCat
Thanks for your reply. I'm new to this, so could you please explain how I could do this? Thanks
Taimur
It is not "nonsense", it is valid SQL. The query returns an empty result set if no rows matching the WHERE clause exist; on the other hand if any rows match, they are returned.
Hammerite
So do you know how I can make it so that if no rows match, it doesn't give mysql error?
Taimur
@Hammerite as the code seems good I thought it could be a kind of query optimization if you want records you already have. After testing it doesn't appear but anyway this method is not recommended.
MatTheCat