I am going to use mysqli_close($connection)
to close the $connection
. But Before Closing I need to ensure that the concerned connection is open.
If you open a connection, it will stay open until it's explicitly closed or the script ends (unless persistent connections is on). Using the code you have should work.
One option is to extend the mysqli
class and have a status property called $connected
:
class CustomMysqli extends mysqli
{
protected bool $connected;
public function __construct($host, $username, $password, $database)
{
parent::__construct($host, $username, $password, $database);
$this->connected = ($this->connect_errno === 0);
}
public function close(): void
{
if ($this->connected) {
parent::close();
$this->connected = false;
}
}
public function isConnected(): bool
{
return $this->connected;
}
}
Checking for the $connected
property is a bit overkill, but will ensure the connection is still open.