Mihkel Viilveer
Mihkel Viilveer

Reputation: 432

Storing user info to session or load them directly from sql when request is made?

Another, maybe dummie, question. I'm making a website and now I've dilemma between $_SESSION and requesting user data directly from the table itself. So, my two ideas right now:

  1. Retrieve needed values from mySQL and then set them to $_SESSION array. So, when I need something I can just call $_SESSION["username"]. It has some disadvantages also. For example, if admin changes some user data, ie username(that is a lame example, but still).
  2. Retrieve value straight from SQL. In this case I can call some function what calls a SQL query and gives me result.

So, question is, which method is better to use or there are any alternatives you can suggest.

Thanks.

Upvotes: 2

Views: 165

Answers (2)

Marc B
Marc B

Reputation: 360882

For frequently-used data but relatively unchanging data, such as names ("Hello, $firstname, welcome back") that would be used on every page request, you probably should cache them in the session. The slight additional parsing/loading overhead will be far less than having to yank that data out of the DB each time.

For relatively critical data, e.g. 'account is disabled', you may want to hit the database each time. However, this would depend on your security needs. If it's ok for a banned user to be able to wander around your system for a short period after their account is disabled, you can implement a time-out counter in the session, e.g. after every 50 hits, you refresh the data in the session regardless.

Upvotes: 3

alpera
alpera

Reputation: 509

do not hold username in SESSION, instead hold user id, and don't let the admin to change the user id. once an account created, it's user id shouldn't be modified. and for each page load check stuff from DB.

Upvotes: 1

Related Questions