简体   繁体   中英

MySQL + PHP - Best way to store timestamp every time user logs in

I need to track all of a user's logins, so that every time they log in I have the timestamp of when they did so. What is the most efficient and best way of doing this?

I have always done it by simply having a text field in the users table that stores unix timestamps separated by a character. Each time they log in, another timestamp gets added to the end.

1243453458|1255476933|1263453743|1318495068|

Is this a bad way of doing it? I figured a separate logins table with a row for every time any user logs in is total overkill and will result in far more strain on the DB when retrieving this information.

Bear in mind I process these timestamps in PHP and also create graphs using jQuery from the data.

Yes, that is a horrible way of storing anything, including timestamps, and there are much better ways of doing this. Even the simplest table would give you much better performance:

user_id (int) | last_login (timestamp)
  • you're storing the timestamps as string. That's completely inefficient for storage, retrieval, and update; plus you'll run into a column limit eventually.
  • there are heavily optimized datatypes for this kind of purpose - the MySQL server developers tend to know a thing or two about storing data efficiently.
  • the database hit for such a tiny table, with fixed-size rows, will be negligible - as opposed to a table with variable-size strings which requires further processing in the application.

In other words, by trying to optimize the app (based on incorrect assumptions - "another table is too much strain"), you've pessimized it, coming up with an all-around inefficient solution. Don't overcomplicate things; and when in doubt, profile both options and see for yourself.

You'd probably be better to put it into a separate table in your database, something like:

members_logins
member_id (int) | timestamp (timestamp)

It'd mean it would be easier to do operations on.

In mysql you can use a TIMESTAMP

Have a look here on how to configure it

EDIT: Your pipe delimited approach is no good. You could have a transactions table storing all sorts of user events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM