PDO MySQL Connection close - unset vs null

10,400

Solution 1

They do the same thing. Unsetting the $pdo handle and setting it null both close the connection.

You can test this for yourself. Run the following script in one window, and in a second window open the MySQL client and run SHOW PROCESSLIST every couple of seconds to see when the connection disappears.

<?php

$pdo = new PDO(..);
sleep(10);
unset($pdo);
echo "pdo unset!\n";
sleep(10);

Then change unset($pdo) to $pdo=null; and run the test again.

<?php

$pdo = new PDO(..);
sleep(10);
$pdo = null;
echo "pdo set null!\n";
sleep(10);

The extra sleep() at the end is there to give you a moment to see that the connection has dropped, before the PHP script terminates (which would drop the connection anyway).

Solution 2

I stumbled with this. I have a PDO object that spans setup and teardown, and I can't find where there must be a remaining reference, as setting $pdo to null did not resolve the problem.

User Contributed Notes in http://php.net/manual/en/pdo.connections.php discusses the problem of delayed closure. Here they suggest killing the current connection:

$pdo->query('SELECT pg_terminate_backend(pg_backend_pid());'); $pdo = null;

This is for postgres. For mysql I have used:

$pdo->query('KILL CONNECTION CONNECTION_ID();');

Share:
10,400
Jacob Cohen
Author by

Jacob Cohen

Web Developer

Updated on June 11, 2022

Comments

  • Jacob Cohen
    Jacob Cohen almost 2 years

    I've read in PDO manual that to close connection you should use the following:

    $connection = null;
    

    However, Some people suggested that since PHP 5.3 has a new GC, the following should be used:

    unset($connection);
    

    I need to know once and for all, which one is preferred, or are they the same?

  • HamZa
    HamZa almost 10 years
    The only small difference I see is that unset() will destroy the variable. Which means var_dump($pdo); would throw an error Undefined variable.
  • Bill Karwin
    Bill Karwin almost 10 years
    @HamZa, thanks, that's true! I should say, they do the same thing with respect to closing the database connection.
  • Your Common Sense
    Your Common Sense almost 10 years
    An answer that answers the OP literally, but does solve not a single problem for the OP. I call it "SO-way".
  • Gabriel
    Gabriel over 8 years
    This is totally untrue, and very bad advice. Some php scripts are long-running, and need to fetch some data from a db before launching a long task, and you don't want to keep one connection slot open in sleep for nothing. There MUST be a proper way to close+free ANY resource in PHP: true for network, db connections, sockets or anything else. Relying on the = null; assignment is very wrong, IMHO.