Sasay
Sasay

Reputation: 101

How to close the MySQLi connection?

have the following code, if I try to execute it in the controller, create an instance of this class and consistently cause get_one, and then get_two, it returns an error because get_two mysql-connection is already closed.

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;

    }

}

Comes to mind only this

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

How to right way?

Upvotes: 2

Views: 8476

Answers (1)

user2395126
user2395126

Reputation: 546

You don't want to close the MySQL connection in each function, but rather upon destruction of the class. As of PHP 5 you can use the __destruct() function. When there are no longer any active references to an object this function is automatically called. Try removing:

$this->mysqli->close();

From get_one() and get_two(). Then add the following function to your 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.";
    }
}

This will allow your connection to close upon destruction of the class.

Upvotes: 4

Related Questions