Home » Php » mysql – Cache data in PHP SESSION, or query from db each time?

mysql – Cache data in PHP SESSION, or query from db each time?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is it “better” (more efficient, faster, more secure, etc) to (A) cache data that is used on every page load in the $_SESSION array (but still querying a table for a flag to reload the data fresh), or (B) to load it from the database each time?

I’m using the cache method (A), but I’m worried that with hundreds of users, memory could become an issue? It’s just simple data, like firstname, lastname, birthday, etc.

With either method, there’s still a query being run. Thoughts?

How to&Answers:

If your data is used on every pages, and is the same for all users, I wouldn’t cache it in $_SESSION (which means having a different copy of that data for each user), but with another mecanism, like :

  • file
  • In memory, with APC for instance (if only 1 server)
  • In memory, with memcached, for instance (if you have several servers)
  • If your data requires long calculations or several DB queries to be obtained, caching it in database could be another possibility (would mean only 1 query to fetch back, and less calculations)

If your data is not the same for each user (which seems to be the case in your situation, as you are caching names, birthdates, …) :

  • I would make sure I only cache what is necessary
  • Once you only have a few data to cache, putting it in session should be quite OK
  • If you really have that many users, you’ll probably have some other scalability problems, and will most likely come to use something like memcached anyway ; which means you’ll have some other way of caching 😉

As a sidenote : if you are doing the same query over and over again, you DB server should cache it by itself (for MySQL, it would go into the “query cache“) ; so, it would not be as bad as you think, I suppose — even if not that much optimized ^^

Answer:

It depends on what you’re session handler is. Your session handler could be MySQL, and thus the question would not be which is better, but how to optimize your session handling.

The default PHP session handler is files, but it can be changed to mysql quite easily.

If you’re talking about non-user specific data, then just save it to the DB. Worry about optimizing if you run into problems later. It is usually much more beneficial to use a better design pattern then thinking about optimizing before hand. Design your code so you can easily use a different handler for storage, and you won’t have optimizing problems later.

If it is user specific, use the session, but use an appropriate session handler if necessary.