I noticed there is no close function for PDO. Should I close the connection or is it unnecessary for PDO?
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.
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();
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.
"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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With