How to automatically increment a value in database? (LIVE) - php

I'd love to create great things with number based stuff.
I totally have no idea how / where should I start.
Let's say users have to register then log in to the site to use this feature (already done this).
I tried to save their registration date in timestamp and calculate their value (the one that i need to increment) from the elapsed timestamp since registration. It was working, but when I set a maximum to this value, and then raised it's maximum, it just jumped to the new maximum (since the time was still going). Btw, this thing needs to be working even if the user is completely logged out, and also not on the site. (so it's server sided)
So let's say I need to increment this value by 550 an hour, but after the first hour elapsed the incrementation grows to 650, after the second hour grows to 750 and so on... and as soon as it reached 3272 it must stay there.
It's also important to visually upgrade this value LIVE. So the user doesn't have to refresh the page every time he/she wishes to take a look at their new value. I guess the hard part is that to calculate every second's incrementation value to match the value of the hour. Okay not that hard I guess it must be like 650/60/60 = 1 second
Best Regards,
Henrik

It is not clear what you are trying to do, but you have multiple options.
You can use timestamp itself as a increment value.
Or
You can use cron-jobs. (Google if you need more information about this)
Create a cron to automatically increment your mysql value and set the interval.
Hope this helps.

Related

Is it possible to update an account's database info every some hours if condition is met?

Okay, so this may be a long shot...I'm trying to create a simple online game and I'm wanting to create a php page/function that connects to the mysql server, runs through every account, checking on each 'character' based on time passage (ie if more than 14 hours passed and sleep = 0, then exhausted = 1). Furthermore, I want to track this passage of time based on the users local time. If the character 'sleeps', sleep = 1 and once 8 hours pass, the database will reset exhausted = 0.
Is this possible? I've been searching, but I'm not even sure how to word this right...I'm also open to javascript or another language if someone can point me in the right direction.
Thanks in advance!
I think I've come up with an easier way of accomplishing what I want to do. When the "sleep" button is clicked, the present time stamp will be stored as "sleeptime" and I'll set the "awaketime" for +8hrs (or whatever), storing that time as well. While sleeptime != awaketime 'rest' will continue. I can make certain features unavailable through hidden divs and whatnot, until 'rest' is over.

Implement flood control with redis

I'm trying to replace the sql implementation of Drupal 8's flood control service with a redis based implementation.
See https://github.com/drupal/drupal/blob/8.0.x/core/lib/Drupal/Core/Flood/DatabaseBackend.php
The requirements are like this:
Each occurrence of an action/event (e.g trying to log in) is logged with an expiration, identifier and timestamp
I need to be able to prevent that a certain action can be done more than N times in a given timeframe
I want to be able to clean up expired events
In case of a threshold of 3 in 10 minutes, if the user tries once, then twice after 5 minutes, he is blocked and can try again once after 5 more minutes. Not 10. While the second would be a valid way to do this, it's not how the sql implementation works or how the tests expect it to work.
As you can see based on the API, I also don't know when registering the event what the threshold is, I only know the expiration of a single event.
My thoughts on how to implement this:
If, after N occurrences should be locked for the given time, then this would be easy with a single KEY for event:identifier that is incremented, once the max is reached, it is locked until it expires again and each INCR would also update the expiration (or not).
I found many posts that ask about expiration of list entries, which is not possible. There are workarounds using sorted sets and delete by range. Most seem to use a single global set, but then I can't easily count my event + identifier - I think.
After writing all this down, I might actually have an idea how it could work, so I guess what I'm looking for is feedback on whether that makes sense or if there's an easier way.
Each event:identifier combination is a key and contains a sorted set. That uses the expiration as score and as value a unique value, possibly creation time in microseconds. I count the non-expired records to detect if the threshold was reached. I'm updating the expiration of each event:identifier to the provided expiration window, so it will be auto-deleted assuming unless a given identifier/client doesn't give up and keeps on trying, without ever reaching the expiration. Is it worth to clean up the records inside a set e.g. when doing a new register? It seems to be fairly fast, and I could also only do it sometimes.
I would prefer to use Redis' key expiration feature, instead of reimplementing one.
A simpler alternative would be the following one:
just SET a simple value, which is the the number of attempts; use a key built on a pattern like "identifier":"event type" :
SETNX <identifier>:<event type> 1
if the response is 1, this is the first attempt, so you set a timeout on this key:
EXPIRE <identifier>:<event type> <timeout in seconds>
otherwise you increment the number of attempts
INCR <identifier>:<event type>
The response of the INCR will give you the number of attempts during the window, so you know if you can allow the action or not.
You could also use a hash instead of a simple value, if you need to store more data, like the max number of allowed attempts in the given time window. In this case you will probably use HSETNX and HINCR.

where to implement counter of consecutive visits?

so first of all i checked and researched this question in stackoverflow and google but there no similar question.
i checked Count number of consecutive visits and SQL Query: Visited the site each day for 30 consecutive days but it doesn't help.
so my question is where to implement this action of testing if a user has visited the site for a consecutive x time, in the links that i put there they check in server side, but i think it's not very optimised because each time the user visits the website a query is triggered to check if todays date is equal or higher than LastVisit date.
in my application i already do query every time the user loads a page to retrieve his information but if i add an
update userInfo
set DaysConsecutivelyVisited=DaysConsecutivelyVisited+1
when DATEDIFF(CURDATE(),LastVisit)=1
then i'll have two queries every time the user loads the page, so i tought maybe it's better if i do this in client side rather than in server side. I'll put an attribute or hidden span in the document
<body data-lastvisit="2012-03-25" >
and in the javascript i'll do the analysis and if the $("data-lastvisit") is equal to yesterday i'll send an ajax reqeuest to update the DaysConsecutivelyVisited
what do you think, is it a good idea ?
You'll need a parameter to compare to.. which is - unfortunately - always the data inside your database table. The only thing you can do is to retrieve the userinfo on pageload, which most likely includes a field last_visited. If the date is not equal to todays date, registered it.
Furthermore, I'd say create a field consecutive_visits and reset to 0 in case the date's difference is larger than a day and increment it in case there's a day or less difference. This way you'd always have the amount of consecutive visits in the userobject after fetching it on pageload.
I absolutely do not see any need for an ajax request in this case. It's just a compare of the current user data with a Date() instance or timestamp. All calculating can be done serverside and there's only need for an extra MySQL query in case the values are different.

Timer based status changes that are saved to database

I have a PHP website using a MySQL database.
We have items that users create, that are on a timer, and once this timer has counted down, without user interaction (basically next time someone sees it) the status needs to have changed.
I'm not sure how to implement this in a way to be accurate to the minute.
So we have an object X, that expires at 10:15pm tommorrow, and the next person to see object X after that time has to see it as expired.
Is the correct way to do this to be the next time object X is loaded we check if it's expired, and if so, update the database?
What happens if 10 people load object X at the same time after it's expired, what's to prevent some sort of race condition from all 10 requests attempting to update the database?
Is there a cron job that runs every minute that I can some how make use of, or any type of timer in MySQL to kick off every minute checking for these and running a script?
I have several ideas on how it -could- be done, like those listed above, but I'm not sure what the most practical is, or what the standard way to do it is as I'm positive someone has solved this problem before.
Is the correct way to do this to be the next time object X is loaded we check if it's expired, and if so, update the database?
Why do you need to update the database? It seems like you might have some redundancy in your DB table - from what you've said, it sounds like you have (for instance) an is_expired column and then an expires_at column.
Why not just get rid of the is_expired column? It's cheap to compare 2 integers, so when you want to determine if something is expired, just fetch the expires_at column and compare with the current time. This avoids any race conditions with expiry, since nothing in the DB changes.
You can do it with cron of course. Or with javascript native function setInterval( "checkFunction()", 10000 ); to alter the db. Or you could use a date field in DB and check for expiration
Make a field date_to_expire as DATE , enter the expiration date and everytime you query for it check to see if the item is expired (this can go up to seconds)

PHP, how do I calculate total online time of a user?

What is the best way to calculate the total time spent by a registered user on the site? ...under these conditions
1) User logs out normally.
2) User can simply close browser.
3) User can auto-login next time he comes back.
I think the best way to do this would be to find the time spent by the user on each page and keep adding them to his total time instead of checking for the whole site. But I don't know how to implement that....please help
You can't find the exact time he leaves the system, unless he logs out. Even then, he might be browsing the site while logged out.
The approximate way to do this would be to set the start time in the session and keep incrementing the time everytime he visits a page.
So the first time the user comes to your site at time T, you will
Create a session and put the start time there
Add the total time as 0
For all subsequent requests you would
Check the start time and compare that with the time now and get the difference
Add that time to the total time
This method will not give you the time the user spent on the last page. But it will give you something to work with.
You can do this with JavaScript and a separate PHP script.
The javascript code reacts to events that mean that an user is active (such as mouse/keyboard/resize events) and invokes the php script.
The php script compares the time when it last received a request to the current time and checks if the difference is over a certain threshold (i suggest something like 10-30 minutes to prevent single-click sessions from adding up) nothing happens.
If the threshold is not reached then the difference between the two timestamps is added to the total sum in the database.
Afterwards (in both cases) the last request time is set to the current time and the script ends.
If you also want to know when the user closes your website pages you can subscribe to unload events and/or implement an heartbeat script that calls a PHP script every X seconds.
you have 2 approaches, either to create a log table in your DB to track each user (by ID) logins and logouts and then calculate the time difference between the two in each record for the specific user and then sum all of that. OR you go more complex and make 4 columns in your DB->usertable (logintime 'timestamp' - logouttime 'timestamp' - lastactive 'timestamp' - onlinetime 'int') and update each column as their names say by code according to user activities. then alter the Session.php script in the System/libraries directory at line 105 exactly after if ( ! $this->sess_read()) before the system creates a new session and write a code to check if the 'logouttime' is not the same as 'lastactive' time (to avoid session timeout expiry misunderstood in the next code) if both fields not the same, update your DB to make 'logouttime' equals 'lastactive' then at line 107 exactly after: $this->sess_update(); write a code to check if the 'logouttime' equals the 'lastactive' (and you will make that happen earlier in your logout.php script) write a code to calculate the online time by the difference between the 'logintime' and the now time 'time()' and add the result to the 'onlinetime' field. but if the 'logoutime' is not the same as 'lastactive' (that meanse the user is online and making activities in your site because you are tracking him and updating the 'lastactive' field frequently) then write a code to calculate the online time by the difference between the 'lastactive' and now time 'time()' and add the result to the 'onlinetime' field. that way you have the exactly online time logged forever in the 'onlinetime' field! I hope you got me right because the examples will be a lot long of scripts (although I don't mind to share upon request). good luck.
Use the Session ID to keep track of individual sessions.

Categories