Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php / mysqli: should I free_result before I return?

Tags:

php

mysqli

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

Quoted from php manual: http://php.net/manual/en/function.return.php

So if I were to write this function:

public function check_db_for_desired_value()
{
  //...connect to db, prepare stmt, etc.
  while (mysqli_stmt_fetch($stmt))
  {
    if($column == 'desired_value')
    {
      return TRUE;  
    }
    else
    {
      return FALSE;
    }
  }
  // these commands would never get executed
  mysqli_stmt_free_result($stmt); 
  mysqli_stmt_close($stmt);
  mysqli_close($link);
}

So (if what is says in the php manual is correct) my results get never freed, my stmt never gets closed and my db connection stays open, because I returned something and ended execution of the function...

So should I instead of returning something set the value of a variable and then return this value after closing everything?

I ask, because my code is working and I dont get any errors, eventhough I have written functions like this before...

like image 382
olli Avatar asked Oct 22 '22 14:10

olli


1 Answers

You are correct, nothing is executed after a return.

But you can use __destruct to close connections and clear results:

function __destruct() {
    mysqli_stmt_free_result($this->stmt); // making $stmt a variable inside class
    mysqli_stmt_close($this->stmt);
    mysqli_close($this->link);
}

The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. - PHP.NET

Otherwise you should move the freeing and closing before return is called.

like image 121
Mihai Iorga Avatar answered Nov 03 '22 04:11

Mihai Iorga