我对这个错误感到恼火。我一直在mysqli查询中获得mysqli::query(): Couldn't fetch database
。
这是我的mysqli扩展类(database.php):
class database extends mysqli {
private $host;
private $username;
private $password;
private $database;
private $name;
private $connected;
public $status;
public function __construct( $param ) {
$this->host = $param['host'];
$this->username = $param['username'];
$this->password = $param['password'];
$this->database = $param['name'];
@parent::__construct( $this->host, $this->username, $this->password, $this->database );
$this->status = ($this->connect_errno) ? "Not Connected ( Because of Error )" : "Connected";
$this->connected = ($this->connect_errno) ? false : true;
}
public function stop() {
if( $this->connected ) { $this->close(); }
$this->status = "Not Connected ( Manually Disconnected )";
}
}
这是我使用查询(sessions.php)的地方:
class session {
private $db;
public function __construct( $db ) {
$this->db = $db;
}
function open() {
return true;
}
function close() {
return true;
}
function read( $id ) {
$sql = "SELECT * FROM sessions WHERE sessionid = '{$id}'";
$sqlq = $this->db->query( $sql );
if( $sqlq ) { $row = $sqlq->fetch_assoc(); return $row['data']; }
else { return ''; }
}
function write( $id, $data ) {
$now = time();
$sql = "SELECT * FROM sessions WHERE sessionid = '{$id}'";
$sqlq = $this->db->query( $sql ); // HERE I GET THE ERROR
if( ( $sqlq ) && ( $sqlq->num_rows == 1 ) ) { $sql = "UPDATE sessions SET data = '{$data}', updated = {$now} WHERE sessionid = '{$id}'"; return $this->db->query( $sql ); }
else { $sql = "INSERT INTO sessions ( sessionid, updated, data ) VALUES ( '{$id}', {$now}, '{$data}' )"; return $this->db->query( $sql ); }
}
function destroy( $id ) {
return $this->db->delete( "FROM sessions WHERE sessionid = '{$id}'" );
}
function clean( $max ) {
$old = time() - $max;
return $this->db->delete( "FROM sessions WHERE updated < {$old}" );
}
}
这是我在主文件(main.php)中使用它们的方式:
<?
$params = array();
$params['host'] = XXXXXXXXXXXXX;
$params['username'] = XXXXXXXXXXXXX;
$params['password'] = XXXXXXXXXXXXX;
$params['name'] = XXXXXXXXXXXXX;
include("database.php");
include("sessions.php");
$db = new database( $params );
$session = new session( $db );
session_set_save_handler( array($session, "open"), array($session, "close"), array($session, "read"), array($session, "write"), array($session, "destroy"), array($session, "clean") );
session_start();
?>
答案 0 :(得分:0)
好的,我自己部分地想出来了。无论如何,如果一位经验丰富的PHP开发人员能够更清楚地解释这一点,以便将来的问题和其他人提出的问题,那就太棒了。
似乎如果我在会话方法中检查我的mysqli连接的状态,它会显示“手动断开连接”,这意味着已调用$db->stop()
。我只在我的index.php(我的项目的基本索引)的末尾调用该函数,这基本上意味着会话类中发生的所有事情都发生在整个“外部”PHP代码运行之后。
我通过打开我的数据库类(mysqli的扩展名)的另一个连接,并在会话类中使用该连接来解决我的问题。
答案 1 :(得分:-1)
read function
应该可以正常工作,但write function
无法使用相同的连接。
最好的方法是在特定于类本身的会话对象中创建连接。
会是这样的:
class session {
private $db;
public function __construct( $params ) {
$this->db = new database( $params );
}
.
.
.
}
然后像这样创建会话对象:
$session = new session( $params );