Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何关闭MySQLi连接?_Php_Mysql_Mysqli - Fatal编程技术网

Php 如何关闭MySQLi连接?

Php 如何关闭MySQLi连接?,php,mysql,mysqli,Php,Mysql,Mysqli,有下面的代码,如果我尝试在控制器中执行它,创建这个类的一个实例,并一致地导致get_one,然后get_two,它会返回一个错误,因为get_two mysql连接已经关闭 class Foo extends Bar { function __construct() { parent::__construct(); $this->mysqli = new mysqli($this->cfg->db->host,

有下面的代码,如果我尝试在控制器中执行它,创建这个类的一个实例,并一致地导致get_one,然后get_two,它会返回一个错误,因为get_two mysql连接已经关闭

class Foo extends Bar
{
    function __construct()
    {

        parent::__construct();

        $this->mysqli = new mysqli($this->cfg->db->host, 
                                   $this->cfg->db->user, 
                                   $this->cfg->db->password, 
                                   $this->cfg->db->database);
        $this->mysqli->query('SET NAMES utf8');

    }

    public function get_one()
    {

        $table_one = array();

        $result = $this->mysqli->query('SELECT * FROM `table_one`');

        for ($i=0; $row = $result->fetch_assoc(); $i++) { 
            $table_one[] = $row;
        }

        $result->close();
        $this->mysqli->close();

        return $table_one;

    }


    public function get_two()
    {

        $table_two = array();

        $result = $this->mysqli->query('SELECT * FROM `table_two`');

        for ($i=0; $row = $result->fetch_assoc(); $i++) { 
            $table_two[] = $row;
        }

        $result->close();
        $this->mysqli->close();

        return $table_two;

    }

}
我只想到这一点

public function get_one($keep = false)
{
    ...
    if(!$keep)
      $this->mysqli->close();
    ...
}

如何纠正方法?

您不希望在每个函数中关闭MySQL连接,而是在类被销毁后关闭。从PHP5开始,您可以使用_destruct函数。当对象不再有任何活动引用时,将自动调用此函数。尝试删除:

$this->mysqli->close();
从一号到二号。然后将以下函数添加到类中:

function __destruct()
{
    //try to close the MySql connection
    $closeResults = $this->mysqli->close();

    //make sure it closed
    if($closeResults === false)
    {
        echo "Could not close MySQL connection.";
    }
}

这将允许在销毁类时关闭连接。

为什么要在这些方法中关闭连接?为什么不在析构函数级别关闭它呢?get_one的这两个原型是同一个类的?我创建了这个类的一个实例$foo=$this->loadfoo;并获取数据$data['get_one']=$foo->get_one$数据['get_two']=$foo->get_two;在jther类的一个方法中,只需去掉$this->mysqli->close就可以了——完成后它会自动关闭。要么这样,要么在代码中找出连接的位置,并在最末端找到一个平行点来关闭它……您还可能希望调整for循环以附加每一行,而不是将数组设置为该行的值。使用数组\u push$table\u one$row;和数组_push$table_two$row;