php – Is it necessary to close a connection with PDO after executing a statement?

Question:

I would like to know if I have to close an open connection with PDO after running the CRUD script.

I have read that it is not necessary to explicitly close it, but I have also read that it is better to close the connection to avoid loading the server with so many open connections. The truth is now I do not know what to think with all this and whether or not I close the connections.

Answer:

In theory, a PDO connection closes itself when executing the last statement of the script that uses that connection, so if your code is well conceived you shouldn't have to worry about closing the connections.

From the PHP help :

After a successful connection to the database, an instance of the PDO class will be returned to the script. The connection will remain active for the lifetime of the PDO object . To close the connection, it is necessary to destroy the object making sure that all existing references to it are removed; this can be done by assigning NULL to the variable that contains the object. If not done explicitly, PHP will automatically close the connection when the script finishes .

Note: If other references to this PDO instance still exist (such as from a PDOStatement instance, or from other variables that refer to the same PDO instance), these must also be removed (for example, by assigning NULL to the variable which refers to the PDOStatement ).

Still, some recommend, more out of habit than anything else, closing PDO connections after use. If you decide to close your connections, you must assign null not only to the connection, but to everything that refers to said connection, as explained in the second paragraph of the note indicated above.

There are also discussions about whether a persistent connection or connecting to the database every time is more convenient . There is no definitive answer, it depends on each case, need and development environment.

About persistent connections you can read the following links in the PHP Manual:

In my case, I use a PDO class on my web page with persistent connection and so far I have not had any problems. Simply put, the class that handles connections first investigates if there is no connection already available and if there is not, then it creates a new one. So I just ask for my connection and do my queries, ensuring that the code is optimized, its flow controlled and that the script ends when it has to finish … avoiding calling my connection from loops that for whatever reason could end up being endless, etc. .

I show you the method that does this:

public static function getInstance()
    {
        if (self::$instance == null) {
            $className = __CLASS__;
            self::$instance = new $className();
        }
        return self::$instance;
    }
Scroll to Top