如果我的帖子错了,我的道歉,我的第一个。
我有一个带有mysql后端的多用户应用程序。所有与用户相关的例程(包括会话跟踪)都依赖于mysql表。
我看到的问题是数据库连接偶尔会消失。例如,在导航站点时检查用户会话时,不会从DB返回任何内容,因此用户将被注销(应用程序旨在执行此操作)。所有php类都使用相同的Database类,它提供PDO例程,即db = new Database();
。从我收集的内容来看,我需要在Database类中包含克隆和实例检查,但我不太清楚如何实现它。
非常感谢任何帮助。
<?php
class Database{
private $host;
private $user;
private $pass;
private $dbname;
private $dbh;
private $error;
public function __construct(){
require('config file');
$this->host = host
$this->user = user
$this->pass = password
$this->dbname = dbname
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';port=3306'.';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
PDO::ATTR_EMULATE_PREPARES => TRUE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
error_log(__CLASS__.'::'.$e);
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
try{
return $this->stmt->execute();
}
catch(PDOException $e){
error_log(__CLASS__.'::'.$e);
}
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
public function close(){
$this->dbh = null;
return 1;
}
}
?>