需要关闭会话的数据库连接

时间:2013-06-02 07:05:05

标签: php mysql session pdo

我有以下代码,基本上取自http://www.spiration.co.uk/post/1333/PHP-5-sessions-in-mysql-database-with-PDO-db-objects

让我觉得有点奇怪的是,没有任何内容可以关闭数据库连接(即设置$ this-> db = null)。我应该担心(或其他任何事情)吗?具体来说,我应该在close()函数中放入$ this-> db = null还是close()这里意味着什么呢? :)

public $db;
public $maxlifetime = 1800; /* 30 mins */
public $expiry;

public function __destruct(){
session_write_close();
}

public function open( $path, $name ) {
$this->db = new PDO('mysql:host=' . MySQLConfigClass::MySql_SERVERNAME . ';dbname=' . MySQLConfigClass::MySql_DBNAME, MySQLConfigClass::MySql_LOGINNAME, MySQLConfigClass::MySql_PASS);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return true;
}

public function close() {
return true;
}

public function read($se_id){
$qry = "select se_value from sessions where se_id = '$se_id' and se_expires > " . time();
$sth = $this->db->prepare($qry);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result['se_value'];
}

public function write($se_id, $se_val){
$this->expiry = time() + $this->maxlifetime;
try {
$qry= "insert into sessions (se_id, se_value, se_expires) values('$se_id', '$se_val', $this->expiry)";
$sth = $this->db->prepare($qry);
$sth->execute();
} catch (PDOException $e) {
$qry= "update sessions set se_value='$se_val', se_expires=$this->expiry where se_id='$se_id'";
$sth = $this->db->prepare($qry);

$sth->execute();
}
}

public function destroy($se_id){
$qry = "delete from sessions where se_id ='$se_id'";
$sth = $this->db->prepare($qry);
$tot= $sth->execute();
return ($tot);
}

public function gc($maxlifetime){
$qry = "delete from sessions where se_expires < ".time();
$sth = $this->db->prepare($qry);
$tot= $sth->execute();
return ($tot);
}
}

$session = new Session;
session_set_save_handler(
array(&$session, "open"),
array(&$session, "close"),
array(&$session, "read"),
array(&$session, "write"),
array(&$session, "destroy"),
array(&$session, "gc")
);

session_start();

2 个答案:

答案 0 :(得分:2)

在PDO中,只要数据库对象(由new PDO()创建)被销毁,数据库连接就会自动关闭。请参阅PHP PDO文档中的Connections and connection management

但是,如果在创建PDO对象时设置PDO::ATTR_PERSISTENT => true,则连接将在后续页面加载时进行缓存和重用,前提是它们使用相同的数据库凭据。

答案 1 :(得分:1)

删除对PDO对象的所有引用(例如通过将引用它的变量设置为null)时,将关闭连接。 PHP退出时会发生同样的事情。你无需做任何事情。

此外,您可能会遇到一些错误的SQL注入漏洞!您已经在使用准备好的查询...请务必使用任何变量数据的参数。