关闭MySQL连接(PHP) [英] Close MySQL connection (PHP)

查看:96
本文介绍了关闭MySQL连接(PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个类来创建与MySQL的自动连接并创建查询.看起来是这样的:

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;

现在,我认为在其他php页面中运行某些功能后关闭连接会更好.那么我该如何在课堂上做到这一点(最有效的方法)?

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?

我尝试在课程末尾(在右括号之前)添加mysql_close($this->connection);,但这给我一个错误.

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

推荐答案

您需要将该代码放置在名为__destruct()的函数中,其方式与__construct()相同.参见 http://php.net/manual/zh/language.oop5.decon .php 了解更多信息.

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.

代码如下:

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

请注意,运行此方法时您并不完全知道 :这取决于对象何时被垃圾回收.但是正如Ken在下面指出的那样,执行mysql_close()有利于对称,但不必释放资源.

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.

这篇关于关闭MySQL连接(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆