user3326849 user3326849 - 8 months ago 35
PHP Question

How to free memory in php class method

I present a part of Mine class that works correctly.

But I want your advice in:

How to release resources by

$result->free()
method in function and were to place them in code.

Is it useful to write it at the end of function, when i return value before?
When I have placed it before return operator, function doesn't work.

Thanks in advance!

require_once 'ggc_config.php';

class ggc
{

public static function executequery($querystring, &$id){
$mysqli = new mysqli(_GGC_HOST_ , _GGC_USER_ , _GGC_PASSWORD_ , _GGC_DB_);
if (mysqli_connect_errno()) {
echo("Connect failed: ". mysqli_connect_error());
return 0;
}//if

$mysqli->set_charset("utf8");
$result=$mysqli->query($querystring);
if ($result===true){
$id=$mysqli->insert_id;
return 1;
}//if
else{
return 0;
}//else
$result->free();
$mysqli->close();
}//executequeryi


public static function getresults($querystring){
$mysqli = new mysqli(_GGC_HOST_ , _GGC_USER_ , _GGC_PASSWORD_ , _GGC_DB_);
if (mysqli_connect_errno()){
die("Connect failed: ". mysqli_connect_error());
}//if
$mysqli->set_charset("utf8");

if ($result = $mysqli->query($querystring)){
while ($row = $result->fetch_row()) {
for ($i=0; $i<$mysqli->field_count; $i++){
$a[$i][]= $row[$i];
}//for
}//while
}//if
return $a;
$result->free();
$mysqli->close();
}//function

}//End of CLASS


due to your advicies I have changet mine code like this:

require_once 'ggc_config.php';

class ggc
{
public static function executequery($querystring, &$id){
$mysqli = new mysqli(_GGC_HOST_ , _GGC_USER_ , _GGC_PASSWORD_ , _GGC_DB_);
if (mysqli_connect_errno()) {
echo("Connect failed: ". mysqli_connect_error());
unset($mysqli);
return 0;
}//if

$mysqli->set_charset("utf8");
$result=$mysqli->query($querystring);
if ($result===true){
$id=$mysqli->insert_id;
unset($result);
unset($mysqli);
return 1;
}//if
else{
unset($result);
unset($mysqli);
return 0;
}//else
}//executequery


public static function getresults($querystring){
$mysqli = new mysqli(_GGC_HOST_ , _GGC_USER_ , _GGC_PASSWORD_ , _GGC_DB_);
if (mysqli_connect_errno()){
die("Connect failed: ". mysqli_connect_error());
}//if
$mysqli->set_charset("utf8");

if ($result = $mysqli->query($querystring)){
while ($row = $result->fetch_row()) {
for ($i=0; $i<$mysqli->field_count; $i++){
$a[$i][]= $row[$i];
}//for
}//while
}//if
unset($result);
unset($mysqli);
return $a;
}//function

}//End of CLASS

Answer Source

UPDATE:

Of course, the way you wrote it is somehow wrong. You can not do anything after the return clause because it will end the function execution. You'll need to free the result BEFORE returning.

The way you wrote it, with:

$result->free();
$mysqli->close();

would work as well as soon as you place the return clause after the that.

$result->free();
$mysqli->close();
return $a;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download