數據庫連接,我有以下的代碼,基本上是從http://www.spiration.co.uk/post/1333/PHP-5-sessions-in-mysql-database-with-PDO-db-objects需要關閉會話
這令我有點怪怪的東西舉起的是,有沒有在那裏關閉數據庫連接(即設置$這個 - > db = null)。我應該擔心這個(或其他什麼)?具體來說,我應該把$ this-> db = null放在close()函數中,還是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();
有沒有在這裏的任何地方的對象實際上destoyed? – davidkomer
您發佈的代碼只是一個包裝類,所以當您從其實例化的對象超出範圍時它將被銷燬。 –
如果設置PDO :: ATTR_PERSISTENT => true,這仍然適用嗎? – davidkomer