Jump to content

Properly closing a PDO connection in a function


Strahan
Go to solution Solved by Strahan,

Recommended Posts

Hi.  I always wondered about this..  if I do:

 



function getName($userid) {
  $pdo = new PDO("blah blah blah");
  $sql = $pdo->query("blah blah"); $row = $sql->fetch(PDO::FETCH_ASSOC);
  return $row["UserName"];
  $pdo = null;
}


 

Since the $pdo = null is after the return, does that mean the pdo object isn't getting closed?  I've been doing functions like that this way since I wasn't sure:

 



function getName($userid) {
  $pdo = new PDO("blah blah blah"); $retval = "";
  $sql = $pdo->query("blah blah"); $row = $sql->fetch(PDO::FETCH_ASSOC);
  $retval = $row["UserName"];
  $pdo = null; return $retval;
}


 

I was just wondering if it's necessary, or if the objects clean themselves up automatically anyway?

Link to comment
Share on other sites

you should NOT open a database connection, run one query, then close the database connection. you should open one database connection in your main application code and pass it into any function/class that needs it, then close it after you are finished using it or let php close it automatically when your script ends.

 

to answer your question though, the return statement ends execution of the function code. this causes all variables that are local to the function to be destroyed (unless you defined them as static.) this destroying of the local $pdo variable should cause the connection to be closed regardless of if your $pdo=null; statement gets executed (your second code example) or not (your first code example.)

Link to comment
Share on other sites

Cool, thanks.  So would this be better then?

 

 

<?php
 
  stuff stuff stuff
  $pdo = new pdo blah blah blah
 
  stuff stuff stuff
  $pdo = null;
 
  function dosomething() {
    global $pdo;
    stuff
  }
 
?>
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.