1

I have a global variable for a mysqli connection set like so:

$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbname);

The php manual says:

Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed.

If I reassign the variable to a new connection (using the same code) is this the same as destroying the object? Or do I need to destroy the variable explicitly?

I know I can use $mysqli->close(); but prefer to avoid possible error conditions.

If I do need to destroy the object, is there a simple test to make sure the connection is a valid one first (e.g. using isset)?

mseifert
  • 5,390
  • 9
  • 38
  • 100
  • 1
    Yes, reassigning would *eventually* destroy the object. You shouldn't need to reassign a MySQL connection though…?! Just open one at the start of the script and… that's it. There may be cases where it makes sense to explicitly close a connection when you're sure you no longer need it, but then you wouldn't reopen it…? – deceze Sep 13 '21 at 07:15
  • I was writing an answer when deceze killed your question (probably for a good reason). Nevertheless, the short version of my answer is: The object would be inaccessible to you, so it could as well have been destroyed, but in practice it is not. PHP uses something called [garbage collection](https://tideways.com/profiler/blog/what-is-garbage-collection-in-php-and-how-do-you-make-the-most-of-it). It's nice to know how that works. – KIKO Software Sep 13 '21 at 07:17
  • @deceze - Your answer sparked the real question, as these things often do. I am reassigning the MySQL connection because I need to change the user (for rights reasons) and I thought this was the easiest way. I have since discovered that I can use $mysqli->change_user(username, password, dbname). So, you may be correct that I don't have to close the connection. – mseifert Sep 15 '21 at 05:41

0 Answers0