0

I have a PHP website that includes a "functions.php" script, where a mySQL connection is created. The connection works fine; however I'm getting trouble closing (destroying) it. Even if I place it at the end of said script, the connection is destroyed before some other code is executed and therefore fails. A solution would be to add it to the end every file that includes this script, but I would want to avoid this.

Code:

static $mysqli ;
if(!isset($mysqli)) {
    $mysqli = new mysqli([...credentials...]) ;
}
if($mysqli->connect_error) {
    die("Falló la conexión a base de datos: " . $connection->connect_error) ;
}

Expected result: stable connection, no errors and destruction of connection.

Actual result: either connection is not closed or if closing is destroyed too early.

Can you help me sorting through this? Where should I place a $mysqli->close() line?

Thanks!

alvaroz
  • 1
  • 1
  • You can use a `register_shutdown_function` (https://www.php.net/manual/en/function.register-shutdown-function.php) that is called when PHP is ending if you want to keep the connection open. However, unless youre dealing with high amounts of traffic, theres no downside to closing the connection, and reopening it. For that see: https://stackoverflow.com/questions/16319306/how-to-check-whether-mysqli-connection-is-open-before-closing-it – Erik Baars Jul 10 '19 at 19:31
  • 4
    You don't usually have to explicitly close the connection. It terminates at the end of the script. – Qirel Jul 10 '19 at 19:32
  • "before some other code is executed" Is that "other code" executed during the same request from the same file or an included file? It isn't exactly clear what the logic flow is here, and what the exact problem is. – Patrick Q Jul 10 '19 at 19:33
  • @PatrickQ thanks for your reply. A php file, let's call it test.php, includes at the very top the "functions.php" with the DB connect code. The test.php does a bunch of DB stuff; but when adding a "destroy" line to the end of "functions.php", said "stuff" is executed, apparently, when the connections has been closed, as it throws errors. Does this makes it clearer? Thanks again! – alvaroz Jul 11 '19 at 02:26
  • If you're including functions.php at the top of test.php, then the _entire_ contents of functions.php is going to be executed before any of the code in test.php is executed. That means that you're basically opening and then immediately closing your connection, before you do anything with it. As others have said, there is usually no need to manually close your connection. Just let PHP do that automatically. – Patrick Q Jul 11 '19 at 11:59
  • Thank yoy @PatrickQ! That is what I needed to know. Cheers! :) – alvaroz Jul 11 '19 at 14:32

0 Answers0