ThingEngineer / PHP-MySQLi-Database-Class

Wrapper for a PHP MySQL class, which utilizes MySQLi and prepared statements.
Other
3.3k stars 1.34k forks source link

DB connection is not closing with any function #1025

Closed mukesh-9 closed 4 months ago

mukesh-9 commented 9 months ago

I tried this but my both echo statement displaying the connected database with each closing function i tried-

$DB = new Mysqlidb( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME ); echo '

';print_r($DB);
// $DB->close();
// $DB->__destruct();
$DB->disconnect();
echo '
';print_r($DB);exit();

huseyinaslim commented 8 months ago

This function triggers the close function of the PHP MySQLi extension to close the database connection. It ensures the termination of the MySQL connection on the server side. You have tested it by printing your created db variable; however, this function does not unset a variable or work by destroying it.

public function disconnect($connection = 'default')
{
    if (!isset($this->_mysqli[$connection]))
        return;

    $this->_mysqli[$connection]->close();
    unset($this->_mysqli[$connection]);
}

The disconnect function of the class does not work reliably in some cases, instead we can trigger the close function ourselves by calling the mysqli reference from within the class.

$DB->mysqli()->close();

You can test whether the database connection is closed by trying to execute a query after closing the database connection. You will see that you receive a connection error.

<?php

$DB->mysqli()->close();
$test = $DB->get('sample_table'); // Error: mysqli object is already closed

Or,

<?php

var_dump($DB->ping());
$DB->mysqli()->close();
var_dump($DB->ping()); // Error: mysqli object is already closed

Additionally, you can check if your connection is active by using the ping function of the library.

<?php

var_dump($DB->ping());
$DB->mysqli()->close();
var_dump($DB->ping()); // Error: mysqli object is already closed

If you want to destroy the database instance assigned to the db variable after disconnecting the connection, you can set it to null or destroy it with unset. However, this does not mean that the connection is cut off. First, you should disconnect the connection, and then if you no longer need it, you can unset the instance in this way;

<?php

$DB->mysqli()->close();
$DB = NULL;
//or
unset($DB);

Important note: If your database connection is a persistent connection, it is mentioned on the relevant php.net page that the close command of the mysqli extension may not be effective in closing the connection.

Good day