Jump to content

Properly closing connections?


Strahan

Recommended Posts

I was curious..  I read that after using a PDO connection you should set the object to null to close it out.  In this instance:

 

function IsOwner($regionid, $user) {
  global $Username, $SQL_Server, $SQL_User, $SQL_Pass;
  $pdo = new PDO("mysql:host=$SQL_Server;dbname=$SQL_Database", $SQL_User, $SQL_Pass);
  $sql = $pdo->prepare("SELECT count(region_id) FROM region_players WHERE region_id = ? AND user_id = ? AND owner = 1"); $sql->execute(array($regionid, $user));
  if ($sql->rowCount() == 0) { return false; } else { return true; }
  $pdo = null;
}

 

Since the return is called prior to the nulling, does it leave a connection hanging or does PHP do some sort of auto-closeout when a function ends?  Should I instead be doing:

 

function IsOwner($regionid, $user) {
  global $Username, $SQL_Server, $SQL_User, $SQL_Pass;
  $ownerstatus = false;
  $pdo = new PDO("mysql:host=$SQL_Server;dbname=$SQL_Database", $SQL_User, $SQL_Pass);
  $sql = $pdo->prepare("SELECT count(region_id) FROM region_players WHERE region_id = ? AND user_id = ? AND owner = 1"); $sql->execute(array($regionid, $user));
  if ($sql->rowCount() > 0) $ownerstatus = true;
  $pdo = null;  return $ownerstatus;
}

 

?

Link to comment
https://forums.phpfreaks.com/topic/259021-properly-closing-connections/
Share on other sites

The PDO object will close the connection when it's destroyed.  This will happen once it goes out of scope and is no longer accessible.  There is no need to explicitly set it to null or call unset() for this.

 

In your case, the object will go out of scope when you leave the function, so it will be destroyed automatically at some point after that.

 

In any case, it will be closed when the page is done executing as everything is destroyed at that point.

 

 

Note that the connection may not be immediately cleaned up when the object goes out of scope.  It will happen during the next GC cycle which might occur a little later, or at the end of the script, depending on PHP's memory needs.

 

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.