I’m trying to modify a script that stores my session data in a database rather than the default but I’m having a bit of trouble as I keep getting the error above. It says I’m getting the error on lines 176 and 201.
Here is the function inside the sessionPdo class
public function _write($id, $sessionData)
{
$session = $this->fetchSession($id); // line 176
if( $session === false ) {
$stmt = $this->db->prepare('INSERT INTO sessions (id, data, unixtime) VALUES (:id, :data, :time)');
} else {
$stmt = $this->db->prepare('UPDATE sessions SET data = :data, unixtime = :time WHERE id = :id');
}
$stmt->execute( array(
':id' => $id,
':data' => $sessionData,
':time' => time()
));
if( $this->transaction ) {
$this->db->commit();
}
}
And here is the fetchSession method in case it helps.
public function fetchSession($id)
{
$stmt = $this->db->prepare('SELECT id, data FROM sessions WHERE id = :id AND unixtime > :unixtime');
$stmt->execute( array(':id' => $id, ':unixtime' => ( time() - (int) ini_get('session.gc_maxlifetime') ) ) );
$sessions = $stmt->fetchAll();
if( $this->transaction ) {
$this->db->commit();
}
return empty($sessions) ? false : $sessions[0] ;
}
I’ve struggled to find what I’m doing wrong as all the solutions I’ve found are because the programmer tried to call $this from outside of the class. I’m new to PDO so thanks in advance for any help you can give.
Yeah, the problem is that you are calling
_write()statically. You need to read up on the difference between static and instance methods. I apologize for not explaining it here but there are probably 5,000 people on SO alone who have run into the same problem, which is solved with about 15 minutes of applied reading.When you’re comfortable with that, research the Singleton and Factory patterns, which are two ways of providing access to object instances from a static context and are commonly applied in this situation.