Hi,

I am trying to build a registration system, where user needs to input username, password and email.
I use a checking procedure to make sure that username for each user is unique.

Right now I already try a few way to solve this.
At first, the notice appear when the username is already exist.
Now, the notice appear when i create a new username and the registration is successful.

Below is my code

//check for unique name

$qry = "SELECT * FROM $tbl_name WHERE username = '" . $_POST['username'] . "' ";
echo $qry;

$check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
if (!$check1) 
{ 
echo mysql_error();  
} else { $check2 = mysql_fetch_object($check1); var_dump($check2); } $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'"); $rows = mysql_num_rows($check1); if ($rows == 1) { // a similar name exists, issue error message. echo "error"; } $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'"); if (!$check1) { echo mysql_error();
} else { }

The error message if I enter a new user is
SELECT * FROM test WHERE username = 'chicken'
boolean false

Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 70
Registration Succesful
Click Here to login to your account

Line 70 is
if($check2->username == $_POST['username'])

The error message if I enter an existing user id
SELECT * FROM test WHERE username = 'burger'
object(stdClass)[1]
public 'id' => string '46' (length=2)
public 'username' => string 'burger' (length=6)
public 'password' => string '6e69685d22c94ffd42ccd7e70e246bd9' (length=32)
public 'email' => string 'burger' (length=6)
errorSorry but username "burger" is taken

How to solve this notice? or are there any better way to do the username checking to avoid this notice?
Thanks in advanceπŸ™‚

    roy17 wrote:

    Right now I already try a few way to solve this.

    It helps not to try them all at onceπŸ™‚.

    $check2 represents a user that is recorded in the database. If there is no user with the given name, $check2 will be false (like the var_dump() says), and not an object (like the Notice says).

    Since by definition the user represented by $check2 has the same username as the one supplied, you don't need to check that; you only need to check that $check2 is an object.

    It's also important to note two things: first, your code is vulnerable to SQL Injection; and second, the MySQL extension is deprecated.

      Hi,

      I try this code

       //check for unique name            
      $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'"); if (!$check1) { echo mysql_error();
      } else { $check2 = mysql_fetch_object($check1); var_dump($check2); if(!is_object($check2)) { echo"check2 is not an object"; } }

      The message "check 2 is not an object" appear. So it is verified that $check2 is not an object. How can I fix this?

      It's also important to note two things: first, your code is vulnerable to SQL Injection; and second, the MySQL extension is deprecated.

      I am new to php. Do I need to also prevent this on the registration form as I already use the code below in my login.php

      // To protect MySQL injection
      $membername = stripslashes($membername);
      $memberpass = stripslashes($memberpass);
      $memberemail= stripslashes($memberemail);
      $membername = mysql_real_escape_string($membername);
      $memberpass = mysql_real_escape_string($memberpass);
      $memberemail= mysql_real_escape_string($memberemail);

      This is my full code to process the registration

      <?php
      $server="localhost"; // Host name
      $username=""; // Mysql username
      $password=""; // Mysql password
      $db_name="test_db"; // Database name
      $tbl_name="test"; // Table name
      
      //Connect to server
      mysql_connect("$server", "$username", "$password")or die("cannot connect to server");
      //Connect to database
      mysql_select_db("$db_name")or die("cannot select database");
      
      if(isset($_POST['register']))
      {
          //USERNAME CHECKING
          if(!$_POST['username'])
          {
              die('Username is empty');
          }
          else
          {
              //check for invalid character
              $invalid=array('.',',','/','\\',"'",';','[',']','-','_','*','&','^', '%','$','#','@','!','~','+','(',')','|','{','}','<','>','?',':','"','=');
      
          //length of username
          $length = strlen($_POST['username']);
      
          //replace invalid characters
          $_POST['username'] = str_replace($invalid, '', $_POST['username']);
          $test = $_POST['username'];
      
          //if lenghts are different ($len smaller), invalid characters found, so prompt error.
          if(strlen($test) != $length)
          {
              die('Username Error: Username contained invalid characters. You can only use A-Z, 0-9 and the underscore (_).');
          }
          else
          {
              //check for unique name            
              $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
              if (!$check1) 
              { 
                  echo mysql_error();  
              }
              else 
              {
                  $check2 = mysql_fetch_object($check1);
                  var_dump($check2);
                  if(!is_object($check2))
                  {
                      echo"check2 is not an object";
                  }
              }  
      
              $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
              if (!$check1) 
              { 
                  echo mysql_error();  
              }
              else 
              {
                  $check2 = mysql_fetch_object($check1);
                  if($check2->username == $_POST['username'])
                  {
                       die('Sorry but username "'.$check2->username.'" is taken');
                  }
                  else
                  {
                      //PASSWORD CHECKING
                      if(!$_POST['password']) 
                      {
                          die('Error: Password field was blank');
                      }
                      else
                      {
                          if(!$_POST['verifypassword']) 
                          {
                              die('Error: Verify Password field was blank.');
                          }
                          else
                          {
                              if($_POST['password'] != $_POST['verifypassword']) 
                              { 
                                  die('Error: The passwords do not match.');
                              }
                              else
                              {
                                  if(strlen($_POST['password']) < 6 ) 
                                  {
                                      die('Error: Your password is too short. Must be 6 or more characters in length.');
                                  } 
                                  else
                                  {
                                      //EMAIL CHECKING
                                      if(!$_POST['email'])
                                      {
                                          die('Error: Email field was blank');
                                      }
                                      else
                                      {
                                          //check for invalid character
                                          $emailinvalid=array(',','/','\\',"'",';','[',']','-','_','*','&','^', '%','$','#','!','~','+','(',')','|','{','}','<','>','?',':','"','=');
      
                                          //length of username
                                          $emaillength = strlen($_POST['email']);
      
                                          //replace invalid characters
                                          $_POST['email'] = str_replace($emailinvalid, '', $_POST['email']);
                                          $emailcheck = $_POST['email'];
      
                                          //if lenghts are different ($len smaller), invalid characters found, so prompt error.
                                          if(strlen($emailcheck) != $emaillength)
                                          {
                                              die('Email Error: Email contained invalid characters.');
                                          }
                                          else
                                          {                                          
                                              $insertuser="INSERT INTO $tbl_name (username, password,email) VALUE('".$_POST['username']."','".md5($_POST['password'])."','".$_POST['email']."')";
                                              $insertuser2=mysql_query($insertuser);
                                              if(!$insertuser2)
                                              {
                                                  die(mysql_error());
                                              }
                                              else
                                              {
                                                  echo "Registration Succesful";
                                                  echo "<br><a href=login.html>Click Here</a> to login to your account";
                                              }    
                                          }    
                                      }
                                  }
                              }
                          }
                      }
                  }    
              }
          }
      }
      }
      else
      {
      
      }
      ?>
      

      Does my code still vulnerable to SQL injection even if I already put some parameter?

        roy17 wrote:

        The message "check 2 is not an object" appear. So it is verified that $check2 is not an object. How can I fix this?

        Is it broken?

        $check2 is not an object if there were no records in the table with username='$_POST[username]'. What's your problem with this?

        Do I need to also prevent this on the registration form as I already use the code below in my login.php

        Yes.

        Does my code still vulnerable to SQL injection even if I already put some parameter?

        Yes.

          $check2 is not an object if there were no records in the table with username='$_POST[username]'.

          Yes, I understand this point.
          My problem is how do I remove the message
          Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 70
          when I register a new user?

          What I want the system to work is just output
          "Registration successful.
          Click here to login to your account"
          whenever the registration is a success.

          Right now the output is
          Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 70
          Registration successful.
          Click here to login to your account

          Do you understand my problem?πŸ™‚

            roy17 wrote:

            My problem is how do I remove the message

            I've already answered that:

            Weedpacket wrote:

            Since by definition the user represented by $check2 has the same username as the one supplied, you don't need to check that; you only need to check that $check2 is an object.

            When I wrote that I was talking about this line

            if($check2->username == $_POST['username']) 

            I am new to php.

            Well, you've already managed to pick up a few bad habits. As well as those I've mentioned, you've also got "SELECT *" when all you're wanting is to see if there are any matching records.

            Just briefly, here's a quick bit of code that's a bit closer to how I'd write the whole "check if a user with the given name already exists or not" process:

            $db_name = 'test_db';
            $tbl_name = 'test';
            
            $pdo_connection = new PDO("mysql:host=localhost;dbname=$db_name", '***username***', '***password***');
            
            $username_already_exists_sql = "SELECT EXISTS(SELECT 1 from $tbl_name where username=?)";
            $username_already_exists_query = $pdo_connection->prepare($username_already_exists_sql);
            $username_already_exists_query->execute(array($_POST['username']));
            $username_already_exists_result = $username_already_exists_query->fetch(PDO::FETCH_NUM);
            $username_already_exists = $username_already_exists_result[0];
            
            if($username_already_exists)
            {
            	// That username has already been taken
            }
            else
            {
            	// That username is available
            }

            As well as asking the database only what I want to know, it also guards against SQL injection. You won't be able to use it as it stands, of course, because I've written it against the PDO interface (because, for one reason, I don't use MySQL at all, let alone the deprecated interface extension you're using) .

              Maybe the tutorial in my signature would help you better understand user registration, and using mysqli instead of the deprecated mysql library. Maybe not but check it out if you feel.

                Thanks a lot Weedpacket.
                That has solved my problem.
                I misunderstand your sentence and just add another if statement to check if $check2 is an object with the

                $check2->username == $_POST['username'] 

                still exist.

                @, it is an awesome tutorial. Great job. Definitely will try to implement your tutorial.

                  Write a Reply...