如何关闭 MySQLi 连接?

How to close the MySQLi connection?

有以下代码,如果我尝试在控制器中执行它,创建此 class 的实例并始终导致 get_one,然后 get_two,它 returns 一个错误,因为 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 连接,而是在销毁 class 时关闭。从 PHP 5 开始,您可以使用 __destruct() 函数。当不再有对对象的任何活动引用时,将自动调用此函数。尝试删除:

$this->mysqli->close();

来自 get_one() 和 get_two()。然后将以下函数添加到您的 class:

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.";
    }
}

这将允许您的连接在 class 被破坏时关闭。