为什么警告:mysqli_query():无法获取mysqli?
我不明白为什么我删除第14行($ this-> close();)中的代码,它没有错误,但我不删除它然后警告mysqli_query():无法获取mysqli 。它在最后构造? 我的错误:enter image description here 我的代码:为什么警告:mysqli_query():无法获取mysqli?
<?php
class Display extends Awebarts
{
private $conn;
private $tablename;
public function __construct($tablename)
{
$this->tablename = $tablename;
$this->connectToDb();
$this->conn = $this->getConn();
// insert the data into the table
$this->getData();
$this->close();
}
function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY `id` DESC LIMIT 1 ";
if(!$sql = mysqli_query($this->conn, $query)) {
throw new Exception("Error: Can not excute the query.");
} else {
$num = mysqli_num_rows($sql);
while($num > 0) {
//var_dump($data);
$data = mysqli_fetch_array($sql);
$num--;
}
}
return $data;
}
}
class Awebarts
{
private $cxn;
private $conn;
function connectToDb()
{
include "models/Database.php";
$vars = "include/vars.php";
$this->cxn = new Database($vars);
$this->conn = $this->cxn->getConn();
}
function getConn()
{
return $this->conn;
}
function close()
{
$this->cxn->close();
}
}
class Database
{
private $host;
private $user;
private $password;
private $database;
private $conn;
function __construct($filename)
{
if(is_file($filename)) {
include $filename;
} else {
throw new Exception("Error");
}
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->connect();
$this->selectData();
}
function getConn()
{
return $this->conn;
}
private function connect()
{
// connect to the sercer
if(!mysqli_connect($this->host, $this->user, $this->password)) {
throw new Exception("Error: not connected to the server");
} else {
$this->conn = mysqli_connect($this->host, $this->user, $this->password);
}
return $this->conn;
}
private function selectData()
{
if(!mysqli_select_db($this->conn, $this->database)) {
throw new Exception("Error: No database");
}
}
function close()
{
mysqli_close($this->conn);
}
}
?>
的问题是,当你调用getData()
您已经创建后连接被关闭Display
对象。
在构造函数中调用getData()
没有任何意义,因为您不使用/保存返回值。因此,当执行构造函数时,您会打开一个连接,发送一个select查询(您不保存的返回值),然后关闭连接。之后,getData()
调用导致您的错误消息。
您可以保存在私人领域的构造你的getData()
调用的结果,后来进入或从构造函数中删除getData()
和$this->close();
呼叫,从外面给他们打电话。
谢谢你非常好。 –
我通过在类的显示中添加析构函数(){$ this-> close()}来修复错误 –
尝试执行方法的数据库连接::像这样:
private function connect()
{
// connect to the sercer
if(!$connect = mysqli_connect($this->host, $this->user, $this->password)) {
throw new Exception("Error: not connected to the server");
}
$this->conn = $connect;
return $this->conn;
}
它仍然是错误 –
所以'close'有个问题吗?给我们看怎么样? –
也请提供完整的错误信息。 –
如果没有完整的错误,任何事情都只是一个猜测,但试着在查询中的'$ this-> tablename'周围放置大括号'{}'。 – aynber