开发者

Why does echoing $result->fetch_object()->id twice throw the error: "Trying to get property of non-object?"

The second echo below throws the error "Trying to get property of non-object?" The first echo prints fine.

$sql = "SELECT id
        FROM files
        WHERE url = '$url'";

$result = 开发者_StackOverflow$this->mysqli->query($sql);

echo "companyId: " . $result->fetch_object()->id;
echo "\ncompanyId: " . $result->fetch_object()->id;

I've doubled up the echo for simplicity of demonstrating this error. I'm actually trying to check if $result->fetch_object()->id is set and then do something with the value if it is. I can't get that to work correctly because the second time i use it, it throws the error "trying to get property of non-object."

if(isset($result->fetch_object()->id))
    echo $result->fetch_object()->id;


When you use fetch_object() the pointer moves to the next row, so the second time you call it you get the result of the next row or NULL if there are no more rows.

Take a look at the manual; code like this would result in an endless loop if the pointer would not move to the next row:

/* fetch object array */
while ($obj = $result->fetch_object()) {
    printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
}


Make a reference to it:

$result = $this->mysqli->query($sql);
$id = $result->fetch_object()->id;

echo "companyId: " . $id;
echo "\ncompanyId: " . $id;


The mysqli-resultsets works with cursors. This means, if you call fetch_object() the object is fetched (of course), the cursor moves on and now the previously retrieved object not present in the resultset anymore. Retrieve the object into a variable and interact with that, instead of calling fetch_object() multiple times.

$o = $result->fetch_object();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜