Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

drak's avatar
Level 1

Periodically save session data to MySQL

Every time a user clicks a button, their "clicks" session key would be incremented by one. I think it would not be optimal to save that to the database per click since if the button can be clicked really fast.

How can I iterate through all the active sessions every x seconds and save them to the database? Would I create a cronjob for this?

0 likes
3 replies
jlrdw's avatar

Just curious, why do you need to save a users session data. I don't recall that in any lessons by @jeffreyway.

Are you trying to count how many times a user does something, if that is the case, you could setup a counter and a field in a table to track it.

drak's avatar
Level 1

@jlrdw When a user logs on, their session is initialized from their row in the database. I was using clicks as an example but something like "money" could also be used. When a user clicks a button, they fight a monster and gain "money". They can click the button as fast as they want and their money would increment based on the amount they clicked. I'm using Redis for session storage since writing to memory is much faster and more efficient than writing to a file for a database.

But the session should eventually be saved to the database, just not in real-time.

jlrdw's avatar

@drak you can get the final of this session and write to a table. I know you could add a button to click and have user data saved, but I don't know how you would do it automatically.

Even if you save a recent one it still may not be the very last one saved.

But yes I see what you are trying to do, see if having the user safe where they left off would work for you.

Please or to participate in this conversation.