T. Brian Jones
T. Brian Jones

Reputation: 13522

Why does this code using MySQLi throw a PHP Notice : trying to get property of non-object

This code works, and outputs an array as intended, but throws the following error message:

PHP Notice: Trying to get property of non-object...

Here is my code:

$mysqli = new mysqli("localhost","user","pass","database");
$sql = "SELECT keyterm
    FROM keyterms";
$results = $mysqli->query($sql);
while($result = $results->fetch_object()->keyterm)
    $keyterms[] = $result;

Upvotes: 0

Views: 597

Answers (3)

Matteo Riva
Matteo Riva

Reputation: 25060

You get that warning because you look up the property before checking if the cursor returns a valid object. In other words on the last iteration when the recordset has been exhausted, you will have an empty object with no keyterm property.

Upvotes: 2

Tim Stone
Tim Stone

Reputation: 19169

fetch_object() will return null when there are no more results in your result set, so the last iteration of the while loop will attempt to access the keyterm property on a null value.

You should assign the result object to $result and then access the property in the loop body, e.g.:

while($result = $results->fetch_object())
    $keyterms[] = $result->keyterm;

Upvotes: 6

ajreal
ajreal

Reputation: 47321

$keyterms = array();
if ($results  = $mysqli->query($sql))
{
  while($obj = $results->fetch_object())
  {
    $keyterms[] = $obj->keyterm;
  }
}

Upvotes: 3

Related Questions