When I assign the results of the
second query to $results
, what happens
to the memory associated with the
previous results?
When you execute this:
$results = $db->query($query);
If there was something in $results
before, this old content cannot be accessed anymore, as there is no reference left to it.
In such a case, PHP will mark the old content of the variable as "not needed anymore" -- and it will be removed from memory when PHP needs some memory.
This, at least, is true for general PHP variables; in the case of results from an SQL query, though, some data may be kept in memory on the driver-level -- over which PHP doesn't have much control.
Should I be freeing that result before
assigning the new one?
I never do that.
Related to 1, when I do clean up at
the end, is cleaning up just the last
results enough?
When the scripts end:
- The connection to the database will be closed -- which means any memory that might be used by the driver should be freed
- All variables used by the PHP script will be destroyed -- which means the memory they were using should be freed.
So, at the end of the script, there is really no need to free the result set.
When I do try to clean up a result,
should I be freeing it as above,
should I be closing it, or both?
If you close the connection to the database (using mysqli::close
like you proposed), this will disconnect you from the database.
This means you'll have to re-connect if you want to do another query! Which is not good at all (takes some time, resources, ... )
Generally speaking, I would not close the connection to the database until I am really sure that I won't need it anymore -- which means I would not disconnect before the end of the script.
And as "end of the script" means "the connection will be closed" even if you don't specify it; I almost never close the connection myself.