Skip to content
Advertisement

When using MySQL to store session data, is it faster to use db queries instead of session?

I used a guide to redirect session requests to a DB call so I could maintain a session on front and backend PHP (this guide: from : https://culttt.com/2013/02/04/how-to-save-php-sessions-to-a-database/), but that leaves me with a question.

I can see that the session data is stored JSON in the db. Near as I can tell, that means every time I update $_SESSION data, the db is being called and sending the entire $_SESSION var back and forth.

Normally, I would store things in $_SESSION to ease calls to the db, but with DB sessions, that seems like it would make it far worse than normal. Or is using $_SESSION still pretty fast/memory only when reading and not writing?

For example, normally I’d get a user like this:

function get_user(userID) {
    if ($_SESSION['users'][userID]) return $_SESSION['users'][userID];
    $db = db_connect();
    $db->exec("SELECT * FROM users WHERE userID = ?",[userID]);
    $temp = $_SESSION['users'][userID] = $db->get_row();
    return $temp;
}

Point being, would it now be faster to just do the db call every time?

Advertisement

Answer

I’m accepting this comment (pasted as an answer) as the answer (credit to IncredibleHat):


If you only have a few thousand users, you won’t notice much of a difference in use. However if you are talking millions of users, then the constant get/store of the session data to a db table could start to show (by like an extra half second depending on your server). – IncredibleHat

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement