Jump to content

Notice: Trying to get property of non-object


MasterACE14

Recommended Posts

Hello,

 

I'm receiving the following error:

Notice: Trying to get property of non-object in C:\wamp\www\log.php on line 17

I'm absolutely stumped as to why I'm getting this error and hope someone can shed some light on the problem...

here's line 17:

$atack = getAtack($_GET['id']);
echo "<h2>".$atack->userID."</h2>"; // line 17

and here's the getAtack(); function:

function getAtack($id)
  {
      $str = "select * from `AtackLog` where  ID='$id' ";
      //echo $str;
      $q = mysql_query($str);
      if (!$q) {
          echo('Query failed: ' . mysql_error());
          return;
      }
      if (!mysql_num_rows($q)) {
          return 0;
      } else {
          
          $st = "";
          $st = mysql_fetch_object($q);
          return $st;
      }
  }

 

appreciate the help.

 

Regards, Ace

Wow, what an awful function. This is one reason why Java methods make it mandatory to state what type to return. Your function does one of 3 different things at completion:

 

1. Exits and returns nothing.

2. Return 0

3. Return an object

 

The problem with that is that it is a pain to check. For 1, you have to check if it returns anything. And then check if the value is 0 or not. It's bad. Terrible.

 

So that means, when you run:

$atack = getAtack($_GET['id']);

 

You don't know what you're going to get. So if getAtack() doesn't return the object, $atack->userID would obviously fail because neither the first or second choices are objects and they would not have a userID member.

 

I suggest you change getAtack().

I would throw an exception on error, return null when nothing is found and the object when it exists. This way you can do like this:

 

try {
    if ($attack = getAttack($_GET['id'])) {
        echo 'do something here';
    }
    else {
        echo 'not found';
    }
}
catch (Exception $e) {
    echo 'something fucked up: ' . $e->getMessage();
}

 

Also, you need to make sure you protect against SQL injections in getAttack().

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.