Recently I was having an issue where it was necessary for my database connection to disconnect before continuing on with my script. The documentation for PDO says that for to disconnect you need only set your connection object to
NULL. That was not working for me however.
The common reason such a thing would not work is due to having multiple references to the connection and not cleaning them all up. That was not the issue in my case as everything was contained in a small function that connected, ran a couple queries, then set the connection to
NULL. By the time the function returned the object should be destroyed and the connection closed.
After a bunch of trial and error and documentation/source reading I finally found the culprit. The SQLSRV driver has an option called
ConnectionPooling which if not disabled will preserve the connection for reuse. Disabling this allowed the connection to close immediately.
So if you find yourself in this situation where you can't seem to get PDO to disconnect from SQL Server, make sure you disable this option.
$pdo = new PDO('sqlsrv:server=.;TrustServerCertificate=1;ConnectionPooling=0', $username, $password, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8 ]);