Daniel Hunter
Daniel Hunter

Reputation: 2866

session variables best practice over multiple database queries

I have a page that pulls 2-3 chunks of data from sql. these chunks are broken into about 20 different variables.

Each page you navigate to will use the same data over and over.

Question:

should i place all the variables in session variables or should i query the database on each page, re-establishing the data and variables each time.

some of the pages modify the database and subsequently the variables.

Thanks.

Upvotes: 0

Views: 787

Answers (2)

Vyktor
Vyktor

Reputation: 20997

You should store data in $_SESSION whenever possible (assuming it's not a large amount of data and it's used always over and over and over).

Your greatest problem than would be what will happen if data changes. You may refresh them from time to time with code such as:

if( rand(0,100) < 10){
   readSessionsFromPost();
}

The another way is to modify local file and check it in every request via mtime (and store last value in $_SESSION). Or you can use:

$time = $db->fetch_one( 'SELECT MAX(mtime) FROM pages');
strtotime( $time) >= $_SESSION['time'];

To sum up.

If you don't care that user gets current data 20 requests later, you should go with rand (I actually would care and would never use this :) ).

If you have access to configure file access you should use mtime and modified time (no request on database required).

And if you're having just few users and great reserve in server performance you should just load them every time (or when data changes every few seconds).

Cache adds some overhead and you must decide whether caching those data is performance critical.

Upvotes: 1

linepogl
linepogl

Reputation: 9335

Yes, it would be good to have a caching mechanism. However, php's session variables are not the best solution. You could use a caching system such as APC or MemCached, or you could simply store them into a file on the hard disk.

Reasons not to use session variables:

  1. The scope. I bet that some of your variables may have a wider scope than a session. In other words, some of the variables may be shared between different sessions.

  2. Eager loading. Every time you call session_start, all the variables are going to be unserialized and loaded whether you need them or not.

Upvotes: 2

Related Questions