Reputation: 13522
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
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
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
Reputation: 47321
$keyterms = array();
if ($results = $mysqli->query($sql))
{
while($obj = $results->fetch_object())
{
$keyterms[] = $obj->keyterm;
}
}
Upvotes: 3