关闭mysql php,关闭MySQL连接(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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值