如何在关闭mysql连接前检查连接是否打开


How to Check Whether mysqli connection is open before closing it

我将使用mysqli_close($connection)关闭$connection。但是在关闭之前,我需要确保相关的连接是打开的。

我试着

if($connection)
{
  mysqli_close($connection);
}

但它不起作用。有解决方案吗?

这是来自PHP.net。

面向对象风格


<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s'n", $mysqli->connect_error);
    exit();
}
/* check if server is alive */
if ($mysqli->ping()) {
    printf ("Our connection is ok!'n");
} else {
    printf ("Error: %s'n", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>

程序风格


<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s'n", mysqli_connect_error());
    exit();
}
/* check if server is alive */
if (mysqli_ping($link)) {
    printf ("Our connection is ok!'n");
} else {
    printf ("Error: %s'n", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>

虽然有些人建议检查$connection->ping(), $connection->stat()mysqli_thread_id($connection),但如果连接之前关闭,这三个将抛出:' Couldn't fetch mysqli '。

我的解决方案是:

if(is_resource($connection) && get_resource_type($connection)==='mysql link'){
    $connection->close(); //Object oriented style
    //mysqli_close($connection); //Procedural style 
}

PS:在受控的上下文中,仅检查它是否为资源就足够了。

您可以检查mysqli服务器信息是否设置。

$connection = new MySQLi('localhost', 'user', 'pass', 'db');
if(!isset($connection->server_info)){
    echo 'sql connection is closed';
}else{
    $connection -> close();
}

不要关闭它。这将是最好的解决方案。

99.9%的情况下,你完全可以不去管这个连接,PHP会为你关闭它。

只有当您的脚本必须执行一些不涉及数据库交互的繁重耗时任务时,您可能希望在开始此操作之前关闭连接。但是在这种情况下,您将故意打开连接,因为没有随机的闭包分散在代码周围,因此不需要检查它是否已经关闭。因此,在这种特殊但极其罕见的情况下,只需关闭它。

其他时候别管它。

如果您打开一个连接,它将保持打开状态,直到显式关闭或脚本结束(除非打开了持久连接)。使用已有的代码应该可以工作。

一种选择是扩展mysqli类,并拥有一个名为$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;
    }
}

检查$connected属性有点过分,但可以确保连接仍然打开。

接受的答案对我不起作用,因为在连接上调用函数会抛出couldn't fetch mysqli错误,如果它已经关闭。我在关闭连接之前和之后检查了mysqli对象:

// Before calling $connection->close()
object(mysqli)#92 (18) {
  ["affected_rows"]=>
  int(0)
  ["client_info"]=>
  string(14) "mysqlnd 7.4.23"
  ["client_version"]=>
  int(11111)
  ["connect_errno"]=>
  int(0)
  ["connect_error"]=>
  NULL
  ["errno"]=>
  int(0)
  ["error"]=>
  string(0) ""
  ["error_list"]=>
  array(0) {
  }
  ["field_count"]=>
  int(0)
  ["host_info"]=>
  string(73) "host.rds.com via TCP/IP"
  ["info"]=>
  NULL
  ["insert_id"]=>
  int(0)
  ["server_info"]=>
  string(10) "1.1.1-log"
  ["server_version"]=>
  int(11111)
  ["sqlstate"]=>
  string(5) "00000"
  ["protocol_version"]=>
  int(10)
  ["thread_id"]=>
  int(1234567)
  ["warning_count"]=>
  int(0)
}
// After calling $connection->close()
object(mysqli)#92 (3) {
  ["client_version"]=>
  int(11111)
  ["connect_errno"]=>
  int(0)
  ["connect_error"]=>
  NULL
}
基于这些信息,我写了下面这个简单的函数:
private function isClosed() : bool
{
    return !is_int($this->connection->thread_id);
}

检查连接错误。mysqli_connect()总是返回一个MySQLi对象。

使用

:

$mysqli_connection = new MySQLi('localhost', 'user', 'pass', 'db');
if ($mysqli_connection->connect_error) {
   echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else
{
   echo "Connected.";
}

试试这个:

function close_connection(){
    $thread = $mysqli->thread_id;
    $mysqli->close();
    $mysqli->kill($thread);
}

这将关闭你打开的连接使用面向对象的风格,像这样:

$mysqli = new mysqli($db_server, $db_username, $db_password, $db_name);

这是基本思想,但如果您使用的是过程式风格,我相信您可以根据需要自定义代码。