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

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


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.


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.


It really depends on the volume of data you intend to store and the amount of traffic you intend to handle. If the data is minimal and the site does not need to scale beyond one web server, by all means use the default session handler which writes the session data into the filesystem of the webserver.

If you need to scale beyond one box, it is recommended that you store your session data into either a memory database such as memcached or regular database. You can override the session handler in PHP and write your own implementation to store to database when using $_SESSION.