Close MySQL connection (PHP)

前端 未结 3 1303
臣服心动
臣服心动 2021-01-15 07:56

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 {
             


        
3条回答
  •  误落风尘
    2021-01-15 08:44

    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.

提交回复
热议问题