Jump to content

Freeing MySQLi Objects


cyberRobot

Recommended Posts

I have gotten into the habit of freeing MySQLi result objects once they are no longer needed. However, I'm curious about the cases where multiple MySQLi objects are being used.

 

If I use the same variable to store the result objects, do I still need to call the free() method for each object? Or is an object automatically freed once the variable is overwritten with the new object?

Link to comment
https://forums.phpfreaks.com/topic/291005-freeing-mysqli-objects/
Share on other sites

The results are automatically freed upon destruction of the object. And if your variable is the only reference to the object, then, yes, overwriting it will eventually destroy the object.

 

Note, however, that the old object still exists when you create your new query. That's a problem if you use an unbuffered result and haven't fetched all rows:

$stmt = $mysqli->query('SELECT 1', MYSQLI_USE_RESULT);
$stmt = $mysqli->query('SELECT 1');

This gives you an “Command out of sync” error. If you explicitly free the result, there's no such problem:

$stmt = $mysqli->query('SELECT 1', MYSQLI_USE_RESULT);
$stmt->free();
$stmt = $mysqli->query('SELECT 1');

...overwriting it will eventually destroy the object.

 

I assume that "eventually destory" means that it will be destroyed as soon as the next query executes and the variable is overwritten...is that correct?

 

 

Note, however, that the old object still exists when you create your new query. That's a problem if you use an unbuffered result and...

 

I have yet to use the MYSQLI_USE_RESULT flag, but I appreciate the warning. :)

 

 

 

Thanks for your help Jacques1!

I assume that "eventually destory" means that it will be destroyed as soon as the next query executes and the variable is overwritten...is that correct?

 

It's destroyed after the variable has been overwritten with the new result object (hence the problem above).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.