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
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.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.