Strahan Posted March 15, 2012 Share Posted March 15, 2012 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; } ? Quote Link to comment https://forums.phpfreaks.com/topic/259021-properly-closing-connections/ Share on other sites More sharing options...
kicken Posted March 15, 2012 Share Posted March 15, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/259021-properly-closing-connections/#findComment-1327906 Share on other sites More sharing options...
Strahan Posted March 16, 2012 Author Share Posted March 16, 2012 Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/259021-properly-closing-connections/#findComment-1327947 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.