Click here to Skip to main content
15,888,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Codeproject,

It's my first two weeks of learning HTML, SQL, and PHP. I just finished following a tutorial on a simple register/login system. The simplicity however came with a cost; they did not show you how to check if a username already exists.

The registering and logging in works, but, I'm having troubles implementing my check if username exists.

This is the code that I'm having troubles with:
PHP
$sql="SELECT FROM members WHERE username=123";
if(mysql_num_rows($sql)>=1)
{
    echo"name already exists";
}
else


This is the code that registers the user(After the above code):
PHP
{
           // Fields are clear, add user to database
   // Setup query
   $q = "INSERT INTO `members` (`username`,`password`,`email`) "
   ."VALUES ('".$_POST["username"]."', "
   ."PASSWORD('".$_POST["password"]."'), "
   ."'".$_POST["email"]."')";
   // Run query
   $r = mysql_query($q);
   // Make sure query inserted user successfully
   if ( !mysql_insert_id() )
   {
   die("Error: User not added to database.");
   }
   else
   {
   // Redirect to thank you page.
   Header("Location: register.php?op=thanks");
   }
   } // end if
   }


Could anyone tell me what I'm doing wrong with the "select from" query? I registered around 20 accounts with the username as "123" to see if it was just me messing up the username input, but still no luck!

Edit: Silly me! I forgot to use mysql_query(), this would have never given any result from my database. Fixed code:
PHP
$sql=mysql_query("SELECT * FROM `members` WHERE `Username` = 123");
			if(mysql_num_rows($sql) != 0)    {
				echo"name already exists";
			} else    {}


Best regards,
- Dimitri
Posted
Updated 9-Nov-14 4:35am
v2

Stay away from sql injection too.
 
Share this answer
 
Comments
[no name] 9-Nov-14 10:45am    
Thumbs up...M@dHatter..:)
You need to select something my dear.
SELECT * FROM MEMBERS WHERE USERNAME =anything
Anticipating that your table name is Members
If you wish to select individual columns from the table, then use the column name in place of * separated by commas if more than one column you want to select.
Thanks.
 
Share this answer
 
Comments
Dimitri Nostarik 9-Nov-14 10:28am    
Thank you. The problem was resolved by doing the following query:
SELECT * FROM `members` WHERE `Username` = 123;
[no name] 9-Nov-14 10:45am    
You are always welcome..:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900