Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Carlos Rojas  "Yoru No Tori"
Carlos Rojas "Yoru No Tori"
6,530 Points

PHP with MYSQL driver, PDO and MySQLi drivers, closing a connection

This is some issue I ve been investigating for a good practice for web coding with PHP and a database running in MySQL

As I read in the PHP documentation the PDO driver doesn´t have any close method,

With PDO

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

I know documentation says in some cases it´s not necessary to close your connection but is it true?

Giving the PDO object a null parameter never really sounds for me as a good practice as I follow the process in the actual database, it takes another 60 seconds to close for real your PDO connection, what does it mean?

In other hand, when you work with MySQLi driver you do have a close method

<?php $conn = new mysqli($servername, $username, $password, $dbname); $conn->close(); ?>

This method actually close your connection, so for a big web site with thousands of connections and request, would it be better to work with MySQLi driver and methods?

Thanks

2 Answers

Codin - Codesmite
Codin - Codesmite
8,600 Points

PHP manual quote:

"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."

So in the same way that you would close connection with SQLi:

$this->connection->close();

The equivelant with PDO would be:

$this->connection = null;
Carlos Rojas  "Yoru No Tori"
Carlos Rojas "Yoru No Tori"
6,530 Points

Thanks there, it only was thinking that it would be better in some way to have an specific class or function called end or close or something like that, but you are right that would be the best way to ensure a closing connection