Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are sessions faster than querying the database?

So for example, the user is logging in, and the system is storing informations about them example: birth date, so is faster to get this information from the session, or to query the database for it?

My idea was, that the user needs to login just once and the session is always there, but If I query the database, then if the user reloads the page, the system needs to query again and again, instead of getting the data from a temporary 'place'.

I use PHP and MySQL.

like image 582
Adam Halasz Avatar asked Jul 11 '10 18:07

Adam Halasz


2 Answers

For almost any language and database, yes. A user session is usually just stored in memory, and getting a hold of it is just a matter of looking it up. A database access usually involves some socket communication with a different process. Rather heavy in comparison.

like image 83
Carl Smotricz Avatar answered Nov 02 '22 19:11

Carl Smotricz


How are you doing it all? The way to do is to check the user credentials at the login page and yes there you do have to make a query to check if the user specified criteria match in the database. If they do, you store them in session and then you continue based on that session.

So, it is not about comparison, you have to make to query the database once at the login page and use session afterwards.

Login Page

// database query run once only at this page
// if user exits, you store it into session else redirect with an error message
like image 34
Sarfraz Avatar answered Nov 02 '22 18:11

Sarfraz