0

Let's assume I have 2 php files
In the first one I have the connection to the database. Since I need it in another php files, I assigned it to a global variable like this.

setconnection.php

<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'database';

// Create connection
$GLOBALS['connect'] = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($GLOBALS['connect']->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$db_selected=mysqli_select_db($GLOBALS['connect'],'database');
mysqli_set_charset($GLOBALS['connect'],'utf8');
?>

And then I have another php file in which I use the connection from the above php file.
It is correct to close the connection like this?

index.php

include_once "setconnection.php";
$GLOBALS['connect']->close();
jmarkmurphy
  • 11,030
  • 31
  • 59
Daniel
  • 57
  • 1
  • 8

3 Answers3

0

Good Question! I never see it anywhere in the examples. Closing connection will only save you memory resources. Php is supposed to close non-persistent connection after script execution anyway. However, it may not always be the case. I have had server CPU overloads when legacy code persistently omitted closing connections. As of now, we keep one connection for several functions, which in essence is the same thing you are doing. Works well for us.

Reference: http://php.net/manual/en/mysqli.close.php

Ochkarik
  • 31
  • 5
-1

In my opinion, this is legit. Do not forget to check if the connection is really open or not already closed before closing it.

qdruault
  • 63
  • 9
-1

This is totally legit, as said by Pekka on Are PHP include paths relative to the file or the calling code?,

... remember that include() just inserts code into the currently running script

So, let's say you have a file called example.php:

function example() {
    echo 'Hello, world!';
}

And you include it in index.php:

include 'example.php';
example();

This is the same as having everything in one file:

function example() {
    echo 'Hello, world!';
}

example();

So there's really not any error in closing the connection in another file which is not the one where you opened the connection.

Community
  • 1
  • 1
Condorcho
  • 503
  • 4
  • 12