How can I check if username already exists in database or not.

Just select the record from your DB. If no records found then it doesn't exist. Your checkh will be something like

$resource = mysql_query (select * from ... where username like '$username');
 $num_rows = mysql_num_rows ($resource)
 if ($num_rows == 0) {
   // user record doesn't exist
 }
 else {
   // user record exists
 }

Dont use the like in the select query. Use the following example for better understanding.

This will work if username is unique in your database

$resource = mysql_query("select * from tablename where username= '$username'");
      
      $result = mysql_fetch_array($resource);
      if ($result) {
  
           if($result["username"] == $username && $result["password"] == $password"){
                    // Assing user details to session and redirect to some page.
           }
      }else{
   
             // Assing error message "user record exists"
   
      }

For more articles with code snippets visit at Codershelpdesk.com

Also, you should never store plain text passwords in your database. I would do some research in the php function md5 to create an md5 hash of the passwords and then you can compare the md5 hash version of the password submitted by the user to the md5 hash version stored in the database. You can also use something like aes_encrypt and aes_decrypt which is a very easy way of encrypting and decrypting data with mysql.

That is if you are creating a website and not some school project. You don't want to be in a situation where a hacker gets into your server and starts downloading email addresses and passwords, that would be bad.

Hi Shenba... Try the following code.. This will save the execution time and works faster and easier...

// By this query, you can just select and use only username and password fields alone and it works faster by checking both simultaneously...

$sql=mysql_query("select username,password from table_name where username='$username' and password='$password'");

// This shows if any of the row having the specified username and password.. which means, if the entry occurs in our database...

$ret=mysql_fetch_row($sql);

if($ret>0)
{
echo "Sorry... User already exists";
}

That's all.....You can't check with only username....

If you want "Username" to be the same as "userNAME" instead of them being 2 different users (I.e.: you don't need to type your username exactly how you did when you signed up) you should use the toupper(); function:

if(toupper($result["username"]) === toupper($username))
{
  //user exists
}
else
{
  //user doesn't exist
}
Member Avatar

diafol

Just an extra, perhaps you could ajaxify the name check so that users don't have to submit the form with all their details before being told that username is already taken.

I would also add a check to see if more than one username was returned, this could happen with SQL injection.