Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to close PDO connections

Tags:

php

pdo

I noticed there is no close function for PDO. Should I close the connection or is it unnecessary for PDO?

like image 582
Rujikin Avatar asked Mar 16 '13 01:03

Rujikin


People also ask

Do you have to close PDO connection?

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning null to the variable that holds the object.

What is the method to close the connection in Mysqlli and PDO?

With MySQLi, to close the connection you could do: $this->connection->close(); However with PDO it states you open the connection using: $this->connection = new PDO();

Is it necessary to close connection in PHP?

Originally Answered: Is it necessary to close an MySQL connection in PHP? No (mostly). According to the documentation , database connections are closed at the end of a PHP script for non-persistent connections. MySQL 5.3 introduced persistent connections , which should be closed when you are finished with them.

What happens if you don't close MySQL connection?

"Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."


1 Answers

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

http://php.net/manual/en/pdo.connections.php

So the answer is no, you don't need to do anything unless you need to explicitly close the connection during the script execution for whatever reason, in which case just set your PDO object to null.

like image 95
Stegrex Avatar answered Sep 21 '22 09:09

Stegrex