1

i'm working on a website for my uni work, and it has to allow login access for different users. My tutor has told me I should be using a session variable/array to store all the users data such as first name, address etc.

In my design I just have the userID and Email address (email is used to login) and then functions to get the data from the database as required. He says this would slow the site down as am doing alot of connections to the database.

Should I store all the data in session variables or connect to the database to access this data?

Thanks for any advice :).

Elliott
  • 3,812
  • 24
  • 69
  • 93

2 Answers2

4

You could get the information from the database when they first log in, and then keep it in session variables until they log out or the session times out. Keeping lots of user data in session variables could create some overhead if there are many users logged in at the same time, but it will be different from making constant queries.

The best way to answer might be to ask how much other data exists for users and how much of it is likely to be needed in a "typical" session. The data that most users will require to be loaded at some point during a session could be loaded at login. Data that most users do not need during a typical session could be loaded on demand.

FrustratedWithFormsDesigner
  • 26,726
  • 31
  • 139
  • 202
  • The overhead isnt that big, as its just one Query to get all the user profile and one can expect, that you need the connection later at the request anyway. I dont think, it makes such a big difference. – KingCrunch Nov 18 '10 at 17:01
  • Thanks, I wouldn't be making constant queries to the database, only on certain pages. Such as if they want to view information stored about them. Not every page requires access to the database, but everytime I check the user is logged in I check this via sessions and database, is that correct? – Elliott Nov 18 '10 at 17:01
  • +1 for persist info in the database, but use local values for performance. – Randy Nov 18 '10 at 17:01
  • The user is required to be able to update thier data, when they do this the data held in the sessions would be valid? – Elliott Nov 18 '10 at 17:41
  • @Elliott: If the data being updated is used in many other places, then you would want to store the *updated* data in the session, *after* it's been persisted to the database. Always persist first, and *then* refresh the session vars / cache. – FrustratedWithFormsDesigner Nov 18 '10 at 18:51
2

The answer depends on how "real world" you want to get with your solution. In a real high traffic site that would be load balanced across several servers, the data would be stored in a database and then cached for a period of time using something like memcache upon fetch from the database. If you don't need to get that carried away, then caching in the session is perfectly acceptable.

Sean
  • 4,365
  • 1
  • 27
  • 31