php - SessionHandlerInterface write method alternatives


I'm using the following write method for the SessionHandlerInterface class:

public function write($session_id, $session_data) {
    $sth = DBCxn::get()->prepare("UPDATE sessions SET session_data = ?, last_update = NOW() WHERE session_id = ?");
    $sth->execute(array($session_data, $session_id));
    if ($sth->rowCount() == 0) {
        $sth = DBCxn::get()->prepare("INSERT INTO sessions (session_id, session_data, last_update) VALUES (?, ?, NOW())");
        $sth->execute(array($session_id, $session_data));           

The problem is that ifsession_data for the update query does not changerowCount() will return 0, and in turn the function will try to insert asession_id that already exists and return an error.

I thought as a solution to do a select query to verify whether thesession_id exists or not.

What other alternatives could be used to solve this issue?




read() is called beforewrite() (at the start of the session), and you'd have aSELECT query in there.

Therefore, you already know if you should do anINSERT orUPDATE - just use a property as a "row exists" flag, which you'd set from insideread() and you can later check for that inwrite().

People are also looking for solutions to the problem: php - get the first number in string if there is one


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.