This snippet of code is giving me a problem in an application I'm creating, and when I run it gives me the error above.

$mysqli = new mysqli('localhost', 'username', 'password', 'database');
$ip = $_SERVER['REMOTE_ADDR'];
$userinfo = array();

$result = $mysqli->query('SELECT `ip` FROM `users` WHERE `ip` = ' .$ip. '');
if($mysqli->affected_rows == 0) {
	return NULL;
}

else {
	return $userinfo = $result->fetch_array;
}

Is there something wrong with my code; am I missing something? It would be nice to get an array of a user's information so it's easier to code different parts of my application. The full error message is:

Notice: Trying to get property of non-object in test.php on line 12

    mysqli->affected_rows deals with the result of an UPDATE, INSERT, CREATE statement. For SELECT statements, you want $result->num_rows

      bpat1434 wrote:

      mysqli->affected_rows deals with the result of an UPDATE, INSERT, CREATE statement. For SELECT statements, you want $result->num_rows

      Should have been more precise with my post. I edited it and added more information.

        bpat1434 wrote:

        mysqli->affected_rows deals with the result of an UPDATE, INSERT, CREATE statement. For SELECT statements, you want $result->num_rows

        Thank you. But that only made the problem jump from line 12 to line 7.

        Line 7:
        	if($result->num_rows == 0) {
        
        Line 12: 
        	return $userinfo = $result->fetch_array;
        

        Still giving me the Notice: Trying to get property of non-object error.

          Assume anything can fail, and check for (and handle) all errors:

          $mysqli = new mysqli('localhost', 'username', 'password', 'database');
          if($mysqli === false)
          {
             user_error("Unable to connect to database.");
             return false;
          }
          $query = 'SELECT `ip` FROM `users` WHERE `ip` = ' . $_SERVER['REMOTE_ADDR'];
          $result = $mysqli->query($query);
          if($result === false)
          {
             user_error("Query failed: ".mysqli->error."<br />\n$query");
             return false;
          }
          if($result->num_rows == 0)
          {
             return null;
          }
          else
          {
             return $result->fetch_array;
          }
          
            NogDog wrote:

            Assume anything can fail, and check for (and handle) all errors: ......

            Thank you! That helped a lot, I guess I had a problem with my sql code. I really appreciate your help!

              Write a Reply...