Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store in Session Data vs store in Sql Database for temporary data

I am wondering which is more efficient, to store temporary data (related to that session) in a session using the $_SESSION variable in PHP or store and retrieve from an SQL database?

Thank you for your time.

like image 589
Alec Smart Avatar asked Jun 08 '09 11:06

Alec Smart


People also ask

Can we store session in database?

Yes, you can save them in the database,but there is no need to create a separate column for that.

In which database SQL Server session will be stored?

The session state is stored in the ASPState database. The advantage of this method is that the data is persisted even if you restart the SQL server. Custom storage: Both the session state data and the stored procedures are stored in a custom database.

What kind of data is stored in session?

Cookies are client-side files that are stored on a local computer and contain user information. Sessions are server-side files that store user information. Cookies expire after the user specified lifetime. The session ends when the user closes the browser or logs out of the program.


2 Answers

Keep in mind the session variable is backed by a storage mechanism, that is, when the request finishes the session gets written by the session handler, by default this is to a file. On the next request it is pulled back from that file (or whatever else the session handler uses).

If you're reading and writing this data on every request, just stick with a the $_SESSION variables, the overhead of connecting, querying and updating a database will not be faster than the default $_SESSION.

You'll probably only ever want to use a database backed session if you are running multiple load-balanced servers and need to share the session data between them. In this case, if you find the overhead of the database sessions to be slowing down your site to a noticeable degree you might consider sticking memcached between your web server and the database.

like image 51
linead Avatar answered Oct 01 '22 08:10

linead


I don't know much about reading from a database or a file, but I don't think that "DB access is slower than others" is true. I've learned from my school lessons that Network latency is negligible compared to the I/O access. And if we use DB for sessions, we have some advantages:

We don't have to worried about many servers because there is no file system different.

I also think that storing/reading something to/from a database is more easier than a file system.

Also, if we are using shared hosting, storing sessions in a database is a major advantage for the security.

if i were wrong, please correct me. i still have many things to learn. Thanks.

like image 33
Swan Avatar answered Oct 01 '22 08:10

Swan