user350034
user350034

Reputation:

Close MySQL connection (PHP)

I wrote a class to create an automated connection with MySQL and create queries. Here's how it looks like:

include("constants.php");

class MySQLDB {
    var $connection;

    function __construct() {
        $this->connection = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
        mysql_select_db(DB_NAME, $this->connection);
        mysql_set_charset('utf8', $this->connection);
    }

    // SELECT ALL FROM
    function sf($unit, $table) {
        return mysql_query("SELECT ".$unit." FROM ".$table, $this->connection);
    }
        // and so on...
}

$mysql = new MySQLDB;

Now, I thought it would be better if I close the connection after I run some of this functions in other php pages. So how do I do that (the most effective way) in this class?

I tried adding mysql_close($this->connection); at the end of the class (before the close bracket) but it gives me an error.

Upvotes: 2

Views: 8774

Answers (3)

fire
fire

Reputation: 21531

You probably don't need this if you read the manual it says:

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

If you still want to use it you need to but the function inside of the class...

      function close() {
          mysql_close($this->connection);
      }
          // and so on...
 }
$mysql = new MySQLDB;

Upvotes: 3

Alistair
Alistair

Reputation: 1326

Have a look at the __destruct() method add add that into your class and your close connection in there

Upvotes: 0

MvanGeest
MvanGeest

Reputation: 9661

You'd need to place that code in a function named __destruct(), much in the same way as __construct(). See http://php.net/manual/en/language.oop5.decon.php for more information.

The code would then look like:

include("constants.php");

class MySQLDB {
    var $connection;
    var $sf;

    function __construct() {
        $this->connection = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
        mysql_select_db(DB_NAME, $this->connection);
        mysql_set_charset('utf8', $this->connection);
    }

    // SELECT ALL FROM
    function sf($unit, $table) {
        return mysql_query("SELECT ".$unit." FROM ".$table, $this->connection);
        $this->sf();
    }
        // and so on...

    function __destruct() {
        mysql_close($this->connection);
    }
}

Please note that you don't know exactly when this method is run: that depends on when the object is garbage collected. But as Ken noted below, executing mysql_close() is good for symmetry, but not necessary to free resources.

Upvotes: 2

Related Questions