我不明白为什么我要删除第14行中的代码($ this-> close();),它没有错误,但是我不删除它,然后警告mysqli_query():无法获取mysqli。它在最后构造???
我的错误:enter image description here
我的代码:

<?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()调用没有任何意义,因为您不使用/保存返回值。因此,当执行构造函数时,您打开一个连接,发送一个选择查询(该返回值不保存),然后关闭该连接。之后,getData()调用将导致您的错误消息。

您可以将构造函数中getData()调用的结果保存在私有字段中,以供以后访问,也可以从构造函数中删除getData()$this->close();调用并从外部调用它们。

关于php - 为什么警告:mysqli_query():无法获取mysqli?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39491358/

10-13 07:37