Log when users log in, log when users log out. If they don't logout, you can eighter have it automated (see tips&tricks) or suppose that they have left is they have been inactive for a certain number of minutes.
You should indeed use a db to hold all that information. Just hold the logged in user-data in your db... that is, login-time and session-id.