如何在MySQLi和OOP PHP中检查数据库连接是否已关闭?

问题描述 投票:0回答:1

我可以使用以下两个类打开和查询数据库,但我不确定是否在此行正确关闭了数据库连接

 $this->conn->close(); 

我尝试使用ping()测试这个,但我没有在页面上得到任何东西

   if($this->conn->ping()){
       echo "still Open";
   }
   else{
       echo "It is Closed";
   }

我应该如何以及在何处关闭连接并进行测试?

<?PHP
class dbconnect {
    public $DBSERVER;
    public $DBUSERNAME;
    public $DBPASSWORD;
    public $DBNAME;

    function __construct() {
    }    
    protected function DbStart(){
        $this->DBSERVER     = "localhost";
        $this->DBUSERNAME = "root";
        $this->DBPASSWORD = "";
        $this->DBNAME   = "ttmmyyyy";
        $conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        return $conn;
    }
}
?>

<?PHP
include_once('dbconnect.cls.php');
class SetMetas extends dbconnect {
    private $page;
    private $region;

    function __construct() {
        $this->conn =  $this->DbStart();
    }

   public function GetData($vID){
        $this->id   = $vID;
         if ($stmt = $this->conn->prepare("SELECT `name`,`pricw` FROM orders WHERE `id` = ?")){
            $stmt->bind_param("s", $this->id);
            $stmt->execute();
            $stmt->store_result();
           if($stmt->num_rows === 0) exit('No rows');
            $stmt->bind_result($namerow,$pricerow);
            $stmt->fetch();
            return array(
                'name'         => $namerow, 
                'price'       => $pricerow
            );
            $stmt->free_result();
            $stmt->close();

            $this->conn->close();   
    if($this->conn->ping()){
     echo "still Open";
    }
    else{
     echo "It is Closed";
  }
          }

    }
}
?>
php mysqli
1个回答
0
投票

您可以像这样重写dbconnect类

<?PHP
class DbAdapter {
    protected $DBSERVER;
    protected $DBUSERNAME;
    protected $DBPASSWORD;
    protected $DBNAME;
    protected $conn;

    public function __construct(){
        $this->DBSERVER     = "localhost";
        $this->DBUSERNAME = "root";
        $this->DBPASSWORD = "";
        $this->DBNAME   = "ttmmyyyy";
    }

    public function connect()
    {
        $conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $this->conn = $conn;
    }

    public function closeConnection(): bool
    {
        return mysqli_close($this->conn);
    }
}
?>

mysqli_close功能

成功时返回TRUE,失败时返回FALSE。

所以你可以相应地测试它。

© www.soinside.com 2019 - 2024. All rights reserved.