Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$stmt->close() vs $stmt->free_result()

I am trying to clarify the difference between $stmt->close() and $stmt->free_result() when finalizing a prepared mysqli statement.


So far I use:

$mysqli = new mysqli(host,user,password,database);
$stmt = $mysqli->prepare(sql statement);
[...]
$stmt->free_result();
$mysqli->close();

and everything seems to work fine.

But I've seen a lot of programmers use $stmt->close instead of $stmt->free_result(). And once I've seen both of them:

$stmt->free_result();
$stmt->close();
$mysqli->close();

So what should I choose, under which circumstances and why?

like image 742
Nicholaos Renessis Avatar asked Oct 23 '13 01:10

Nicholaos Renessis


People also ask

What is Free_result?

$stmt->free_result() frees up memory related to a result set, whereas $stmt->close() frees up memory related to a prepared statement. Subsequently calling $stmt->close() will cancel any result still remaining.

What does stmt mean in SQL?

The variable $stmt holds an object of type mysqli_stmt , which represents a prepared statement.


2 Answers

$stmt->free_result() frees up memory related to a result set, whereas $stmt->close() frees up memory related to a prepared statement. Subsequently calling $stmt->close() will cancel any result still remaining.

In essence, calling $stmt->close() will provide the same effect as calling $stmt->free_result() since it cancels the result set as well. But calling $stmt->free_result() will not clear out the memory used by the prepared statement in which case you must use $stmt->close().

As far as which one to use goes - there may be situations where you intend on using the prepared statement you have initialized, but are no longer in need of the result set you currently have. In such a case you would wait on calling $stmt->close() until you are done with the prepared statement and instead call $stmt->free_result() before executing another statement.

like image 167
Crackertastic Avatar answered Sep 17 '22 15:09

Crackertastic


PHP will end your connection and free the resource after it finishes running;

mysqli::close Closes a prepared statement.

Since the number of total connections available is limited, freeing the resource the second you're done with it is a good practice.

And

mysqli_stmt::free_result Frees stored result memory for the given statement handle.

it's good practice to free explicitly the resource when you don't need them anymore. it might avoid make a heavy load into the server when many requests are made at the same time.

Both aren't never strictly necessary to invoke, and is a good practice the use of both.

like image 21
Emilio Gort Avatar answered Sep 21 '22 15:09

Emilio Gort