How to Check Whether mysqli connection is open before closing it

后端 未结 7 1846
野趣味
野趣味 2021-02-04 00:30

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.

<
7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 01:23

    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.

提交回复
热议问题