Jump to content

Properly closing a PDO connection in a function


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?

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

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
  }
 
?>

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.