PDA

View Full Version : Duplicate Entry - If Statement


weaksauce
07-17-2008, 03:27 PM
I have a table called Users, which contains the fields:
{user_name,password,name,user_level,fname,lname}

I have a registration/login process to the site, and my question is how can I make an if statement to test for a duplicate entry during the registration. I only want to test for a duplicate user_name, i dont really care about the first name and last name... and name is for the user type (admin,student, etc.) and user level is an enum. If I try to submit it doesn't allow me to register and it gives me a sql error but I just want to clean it up and maybe on the registration page put a button that can check user_name availability.

Thanks in advance...

abduraooft
07-17-2008, 04:01 PM
You may have to make your user_name a Primary Key.

Just execute a query before adding any rows in to that table, say
select user_name from Users where `user_name` = '$user_name' limit 1 and then check the number of rows returned by this query.

weaksauce
07-17-2008, 04:16 PM
You may have to make your user_name a Primary Key.

Just execute a query before adding any rows in to that table, say
select user_name from Users limit 1 and then check the number of rows returned by this query.


$query = "SELECT Count(user_name) FROM Users WHERE `user_name` = '$user_name'";
$result = mysql_query($query) or die($query . '<br />' . mysql_error());
$num = mysql_result($result,0,0);
print($num);
if($num == 1)
{ die("User Name Exists");}

I used that just as a test, and yeah I set my user_name to a primary index.

abduraooft
07-17-2008, 04:29 PM
There is another useful function to count the number of rows, mysql_num_rows() (http://www.php.net/mysql_num_rows)

I think count() may take some extra time than a simple select with a Limit clause.
PS: I missed the where clause in my OP