In a previous tutorial, I showed you how to connect to MySQL using the PDO object. In this guide, I will show you how to close a PDO connection.
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 and the connection that is associated with that PDO object ceases 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. But that’s an entirely different topic.
Manually closing a PDO connection.
Take 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 the 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! You can close this connection whenever you want to because I’m done using it.”
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;
Note that in 99.99% of cases, this method of closing MySQL connections will be completely unnecessary. We are talking extremely overkill here. Unless you’re knowledgeable about MySQL and what is going on in the background, you should avoid this method.