tags:

views:

656

answers:

4

When I open a MySQL connection in PHP with just PHP's built-in MySQL functions, I do the following:

$link = mysql_connect($servername,$username,$password);
mysql_select_db($dbname);
//queries etc.
mysql_close($link);

When I open a connection with PDO, it looks like this:

$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries

Do I have to explicitly close the connection like I do with mysql_connect() and mysql__close()? If not, how does PHP know when I'm done with my connection?

TIA.

+6  A: 

Use $link = null to let PDO know it can close the connection.

PHP: PDO Connections & Connection Management

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.

DreadPirateShawn
Thanks! Much appreciated.
benjy
+4  A: 

When the PHP script finishes executing all connections are closed, also you don't have to explicitly close your connection with mysql_close()

Vexatus
A: 

http://uk3.php.net/pdo

From what i gather i could not see anyway to close it in the php manual, and examples of scripts i quickly looked at never closed the connection in anyway from what i could see.

Paul Janaway
A: 

You can also limit your connections to within local functions. That way the connection is closed as soon as the function is completed.

JDelage