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开发者_JAVA技巧 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;
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;
$keyterms = array();
if ($results = $mysqli->query($sql))
{
while($obj = $results->fetch_object())
{
$keyterms[] = $obj->keyterm;
}
}
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.
精彩评论