In this tutorial, we are going to show you how to close a PDO connection to MySQL.
Although MySQL connections will automatically close after your PHP script is finished executing, you might come across a scenario where you need to forcibly close them yourself.
MySQL connections will close automatically.
A MySQL connection will automatically close as soon as the current script is finished executing. The connection to MySQL will only stay alive while the PDO object still exists.
Once your PHP script is finished, the PDO object is destroyed. Consequently, the connection that is associated with that PDO object will cease to exist.
PDO is a capsule. Without it, the connection that it holds will simply “die off”.
A connection will only “stay alive” after the script has finished executing if you manually configure PDO to create a persistent connection. However, that is an entirely different topic.
How to manually close a PDO connection.
Take a look at the following example:
$host = 'localhost'; $databaseName = 'test'; $username = 'root'; $password = '3sLS62!)23i3kue<'; //Connect to MySQL via the PDO object. $pdo = new PDO("mysql:host=$host;dbname=$databaseName", $username, $password); //Do something. Run queries, etc. //Close the connection by setting the PDO object to NULL. $pdo = null;
In the PHP above, we connected to MySQL. We then assigned a NULL value to the variable that holds our PDO object.
Note that there is no guarantee that this will immediately kill the connection. In fact, the connection will probably exist for a few seconds afterwards.
Using this method is kind of like saying, “Hey, MySQL! I no longer need this connection. You can close it whenever you want to.”
If you would like to forcibly kill the connection, then you could try something like this:
//Connect to MySQL via the PDO object. $pdo = new PDO("mysql:host=$host;dbname=$databaseName", $username, $password); //Kill the connection with a KILL Statement. $pdo->query('KILL CONNECTION_ID()'); //Set the PDO object to NULL. $pdo = null;
In 99.99% of cases, this method of closing MySQL connections will be completely unnecessary.
We are talking extreme overkill here. Unless you’re knowledgeable about MySQL and what is going on in the background, you should avoid using this method.