我有问题要建立一个连接到DB的代码,然后关闭连接.
我的DB类如下:
class DataBase {
private $conn;
private $info;
private $db;
public function __construct ($servername=DB_SERVER, $user=DB_USER, $pass=DB_PASS, $db=DB_DATABASE) {
$this->db = $db;
$this->conn = new mysqli($servername,$user,$pass, $this->db);
if (!$this->conn)
{
if ($this->conn->connect_error) {
$this->info = "ERROR CODE=DB100: Connection failed <br> " . $conn->connect_error;
$this->close();
echo $this->getInfo();
}
else {
$this->info = "ERROR CODE=DB101: Connection failed <br> ";
$this->close();
echo $this->getInfo();
}
}
}
public function getInfo () {
return $this->info;
}
// send sql to database
public function sendQuery ($sql, $numr=null, $start=null) {
if ($numr) {
if ($start)
$sql .= " LIMIT $start, $numr";
else
$sql .= " LIMIT $numr";
}
$this->conn->set_charset("utf8");
$result = $this->conn->query($sql);
if ($result == true) {
return $result;
}
else {
$this->info = "ERROR CODE=DB102: Sql query not work <br>".$this->conn->error;
$this->close();
echo $this->getInfo();
return false;
}
}
public function sendQueryNoneCahrSet ($sql, $numr=null, $start=null) {
if ($numr) {
if ($start)
$sql .= " LIMIT $start, $numr";
else
$sql .= " LIMIT $numr";
}
$result = $this->conn->query($sql);
if ($result == true) {
return $result;
}
else {
$this->info = "ERROR CODE=DB103: Sql query not work <br>".$this->conn->error;
$this->close();
echo $this->getInfo();
return false;
}
}
// send sql query safe to avoid sql injection.
public function getConn () {
return $this->conn;
}
public function getDataBase (){
return $this->db;
}
// This method close the connection
public function close () {
$this->conn->close();
}
function __destruct() {
$this->close();
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行这段代码时:
$con = @new DataBase();
$r = $con->sendQuery($sql);
$con->close();
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误:
Warning: mysqli::close(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\automasion\admin\protected\componets\database.php on line 102
Run Code Online (Sandbox Code Playgroud)
程序正确运行并将数据设置为DB但发生此错误.
错误指向:
$this->conn->close();
Run Code Online (Sandbox Code Playgroud)
在我的数据库连接代码中.
在构造函数中,您创建了一个mysqli实例:
$this->conn = new mysqli($servername,$user,$pass, $this->db);
Run Code Online (Sandbox Code Playgroud)
但是$this->db 为null并且没有价值.你应该把它改成:
$this->conn = new mysqli($servername,$user,$pass,$db);
Run Code Online (Sandbox Code Playgroud)
还有一件事:
function __destruct() {
$this->close();
}
Run Code Online (Sandbox Code Playgroud)
这个函数在php想要销毁你的对象时运行,但你已经关闭了你的连接!
$con = @new DataBase();
$r = $con->sendQuery("show tables");
$con->close();
Run Code Online (Sandbox Code Playgroud)