如何在关闭mysqli连接之前检查它是否打开

2022-08-30 14:35:37

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

我试过了

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

但它不起作用。任何解决方案?


答案 1

这是来自 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);
?>

答案 2

虽然有些人建议检查 ,或者,如果之前连接已关闭,则三者将抛出:''。$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:仅在它是资源时才检查在受控上下文中就足够了。


推荐