我可以使用以下两个类来打开和查询数据库,但不确定在这一行是否正确关闭了数据库连接
$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";
}
}
}
}
?>
答案 0 :(得分: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);
}
}
?>
成功返回TRUE,失败返回FALSE。
因此您可以进行相应的测试。