Josh Nankin
Josh Nankin

Reputation: 2568

pdo connection wont close once statements have been executed

Using PHP 5.5, I've noticed that I cannot close PDO connections after I've already executed statements using a connection.

For instance:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$dbh = null;

Closes the connection just fine. But I can't get the following connection to close here:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("select * from someTable where 1<>0");
$stmt->execute();
$dbh = null;

Upvotes: 1

Views: 712

Answers (3)

Frank Forte
Frank Forte

Reputation: 2190

You can wrap your database object, and create a __destruct method to close the statement. Careful, I did not test the code below.

class MyPDO extends \PDO
{
    protected $db;
    protected $stm;

    public function __construct($conn_string,$user,$password)
    {
        $opts = [
              \PDO::ATTR_PERSISTENT => true // careful, if connection fails to close, "has gone away" may appear on the next connection.
            , \PDO::MYSQL_ATTR_FOUND_ROWS => true
            , \PDO::ATTR_EMULATE_PREPARES => false
        ];
        $this->db =  new \PDO($conn_string, $user, $password, $opts);
    }

    public function prepare($query,$options = [])
    {
        $this->stm = $this->db->prepare($query,$options);
        return $this->stm;
    }

    public function close()
    {
        if(is_object($this->stm))
        {
            $this->stm->closeCursor();
        }
        $this->stm = null;
        $this->db = null;
    }

    public function __destruct()
    {
        $this->close();
    }
}

$dbh = new MyPDO(...);
$stmt = $db->prepare(...);
$stmt->execute();
$dbh = null; // this should call the __destruct method, and ensure everything is closed properly

Upvotes: 0

Reeling
Reeling

Reputation: 343

You can see a related note about this on the PHP docs here http://php.net/manual/en/pdo.connections.php#114822. In short, you need to set the statement and the connection to null.

$stmt = null;
$dbh = null; 

Upvotes: 2

Vilx-
Vilx-

Reputation: 106912

I'm making an educated guess here that $stmt also has an indirect reference to $dbh, since it needs it to fetch data and stuff. Try nulling that too.

Upvotes: 1

Related Questions