Notice: Trying to get property of non-object

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Notice: Trying to get property of non-object

Post by adhi91 »

Hi,

I am trying to create a registration system where I want the user to enter username, password and email.
I want to make sure that the username and email is all different.
Therefore, i use a simple checking.

Code: Select all

    //check for unique name
    $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
    $check2 = mysql_fetch_object($check1);
    
    if($check2->username == $_POST['username'])
    {
        die('Sorry but username "'.$check2->username.'" is taken');
    }
However, this error message always comes out
Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register.php on line 40
//Line 40 is the if 9$check2->username


What am i missing?
Thanks in advance
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Notice: Trying to get property of non-object

Post by social_experiment »

Add this to the sql query to see if any errors are produced; the code is fine so it could be a error with the query causing the issue

Code: Select all

<?php
$check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'") or die(mysql_error());
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Re: Notice: Trying to get property of non-object

Post by adhi91 »

Thanks,
the notice is gone now.
however, why does the query produce an error?
Is this common practive to add

Code: Select all

die(mysql_error()
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Notice: Trying to get property of non-object

Post by social_experiment »

adhi91 wrote:however, why does the query produce an error?
Who knows? If there is a problem connecting to the database the query won't work, if you don't have error checking in place you will be searching the script for hours to find the problem.

die(mysql_error()) is common practise but it shouldn't be used when the site is live as it will reveal details about the error to anyone viewing the page. Throwing an exception or sending an email are examples of how you could deal with the problem

Code: Select all

<?php
 $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
 // for SELECT statements mysql_query will return false if the query fails.
 if (!$check1) { echo 'An error has occured'; }
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Re: Notice: Trying to get property of non-object

Post by adhi91 »

Right now, when I register new user which should not trigger this condition
the notice come out

below is my code

Code: Select all

<?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');
    }
    //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 (_).');
    }
    
This part is the one for name checking

Code: Select all

    //check for unique name
     $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
    // for SELECT statements mysql_query will return false if the query fails.
    if (!$check1) { echo 'An error has occured'; }
    $check2 = mysql_fetch_object($check1);
    
    if($check2->username == $_POST['username'])
    {
        die('Sorry but username "'.$check2->username.'" is taken');
    }

Code: Select all

    //PASSWORD CHECKING
    if(!$_POST['password']) 
    {
        die('Error: Password field was blank');
    }
    if(!$_POST['verifypassword']) 
    {
        die('Error: Verify Password field was blank.');
    }
    if($_POST['password'] != $_POST['verifypassword']) 
    { 
  	die('Error: The passwords do not match.');
    }
    if(strlen($_POST['password']) < 6 ) 
    {
        die('Error: Your password is too short. Must be 6 or more characters in length.');
    } 
    
    //EMAIL CHECKING
    if(!$_POST['email'])
    {
        die('Error: Email field was blank');
    }
    //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.');
    }
        
    $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());
    }
    
    echo "Registration Succesful";
}
else
{
    
}
?>
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Notice: Trying to get property of non-object

Post by social_experiment »

Update your code to include an else statement;

Code: Select all

<?php
if (!$check1) { echo 'An error has occured'; }
else {
    $check2 = mysql_fetch_object($check1);
    
    if($check2->username == $_POST['username'])
    {
        die('Sorry but username "'.$check2->username.'" is taken');
    }
}
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Re: Notice: Trying to get property of non-object

Post by adhi91 »

Still the got the notice
It refer to this

Code: Select all

if($check2->username == $_POST['username'])
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Notice: Trying to get property of non-object

Post by social_experiment »

Do you receive an error when you modify the code to the snippet below; paste the error if present

Code: Select all

<?php
if (!$check1) { echo mysql_error(); }
else {
    $check2 = mysql_fetch_object($check1);
    
    if($check2->username == $_POST['username'])
    {
        die('Sorry but username "'.$check2->username.'" is taken');
    }
}
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Re: Notice: Trying to get property of non-object

Post by adhi91 »

This it the message that I got
Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register.php on line 42
Registration Succesful


The code

Code: Select all

//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);
    
    if($check2->username == $_POST['username'])
    {
        die('Sorry but username "'.$check2->username.'" is taken');
    }
    }
Line 42 is

Code: Select all

  if($check2->username == $_POST['username'])
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Notice: Trying to get property of non-object

Post by social_experiment »

So no mysql releated error?

The problem with the script you pasted is that there is no real structure for dealing with errors; wanting the script to stop executing is preferable but in a development scenario is not very useful, as we are seeing now.

Echo this query to the browser and paste the results here

Code: Select all

<?php
 // this goes where check is done for similar names in the database.
 $qry = "SELECT * FROM $tbl_name WHERE username = '" . $_POST['username'] . "' ";
 echo $qry;
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Re: Notice: Trying to get property of non-object

Post by adhi91 »

So no mysql releated error?
Yes, no mysql error. Just the notice
The message in the browser
SELECT * FROM test WHERE username = 'burgerking'
Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register.php on line 44
Registration Succesful
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Re: Notice: Trying to get property of non-object

Post by adhi91 »

I put the structure in the code

Code: Select all

<?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
        {

Code: Select all

            //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);
                if($check2->username == $_POST['username'])
                {
                     die('Sorry but username "'.$check2->username.'" is taken');
                }

Code: Select all

                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";
                                            }    
                                        }    
                                    }
                                }
                            }
                        }
                    }
                }    
            }
        }
    }
}
else
{
    
}
?>
The output message
SELECT * FROM test WHERE username = 'burgerking2'
Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 52
Registration Succesful


Line 52 still

Code: Select all

if($check2->username == $_POST['username'])
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Notice: Trying to get property of non-object

Post by social_experiment »

Code: Select all

<?php
$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);
            }  
 
?>
Try the code above and paste the result; if that fails make a connection to the database and attempt the section of code that checks for the username existence without any other code present
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
adhi91
Forum Newbie
Posts: 22
Joined: Wed Apr 04, 2012 8:54 pm

Re: Notice: Trying to get property of non-object

Post by adhi91 »

The result

SELECT * FROM test WHERE username = 'burger1'
boolean false

Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 63
Registration Succesful
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Notice: Trying to get property of non-object

Post by social_experiment »

So $check2 isn't an object, that's causing the problem. I'm not sure what the issue is here but you can use an alternative method to check for the presence of a similar name within the database.

Code: Select all

// alternate method
$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.
}
hth
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply