To use sessions or db queries when doing check-up on every page?
I have application that has to check multiple data from user table, in order to create page.
Not just id and password, but other data as well, about 7 parts of information at this moment.
This check-up is done on every page.
Do I load all this data in session, and check it from there, or do I fire query on every page request? Needless to say, there are also other queries going on.
What's better pract开发者_运维知识库ice, regarding optimization?
You should call the data once from the database and store it in a Session Variable. I generally put my user_id, username, email, user firstname & access_levels in a session when the user first logs in, Then I can call them anywhere in my application whilst the user is logged in.
Do not store the password in the session as it would not be required.
You an also create a variable called logged_in and set it to true or false to test against, (i.e: Show the "Account menu if the user is logged in, else show "Register" Menu).
[Update]
Here is a link to the Pro's/Con's of MySQL caching.
Scroll down to the bottom before the comments.
It kinda depends on your site, for a small site query caching would be fine, but if you wanted to develop more scalable applications, You have to keep speed in mind.
How to tell is mysql query cache is enabled: [LINK]
MySQL will cache the query if it's exactly the same as last time, so getting the user information via MySQL is fine. And especially so if you are getting everything via the primary key which is very fast.
Trips to database are slower than accessing sessions. You should definitely use sessions. Just don't forget that if this data changed in a database, it should also be changed in the current session.
If the data doesn't change too much you could cache it to a file ... or cache it to memory using something like memcache.
Then you can include it via this file and set some theshholds on when to fetch from db or just include.
Your question uses "check" - do you mean that you have to validate data on every page request? If so, you probably can't avoid going to the database.
If all you need to do is store data that doesn't change between pages for the same user, you should use sessions. Be sure to read the white paper "PHP is Not Java" on the zend.com website first!
精彩评论