Sandokan
Sandokan

Reputation: 849

When should I close database connection?

I'm connecting to a MySQL database using

$dbh = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);

While reading through forums and tutorials it says that it is good practice (although not vital) to close a database connection as soon as you are finished with it. So my question is this: should I always add $dbh = null; when the last database operation has been executed?

Upvotes: 2

Views: 3040

Answers (2)

0xmtn
0xmtn

Reputation: 2670

In php you do not have to often close the db connections. Because, after your code finished, web server closes all the connections to database, because the execution is ended. But throughout the execution time you should close it quite a bit, for security reasons. But if you created a e.g daemon, you have to close it, more often, for both security and memory reasons. An open connection is always dangerous for direct db attacks, and reserves some memory.

Upvotes: -1

HellaMad
HellaMad

Reputation: 5374

Connections are implicitly closed when a script has finished executing. The only reason you may want to close a connection is if you plan on opening another one; even then, PDO supports multiple concurrent connections.

Upvotes: 2

Related Questions