如何关闭MySQLi连接?

时间:2015-03-22 17:08:32

标签: php mysql mysqli

有以下代码,如果我尝试在控制器中执行它,创建此类的实例并始终导致get_one,然后get_two,它会返回错误,因为get_two mysql-connection已经关闭。

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();
    ...
}

如何正确的方式?

1 个答案:

答案 0 :(得分:4)

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

$this->mysqli->close();

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

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

这将允许你的连接在破坏课程时关闭。