Execute query until timer reaches zero (PHP and MySQL) - php

I'm doing a module of rental videos, I've done the shopping cart but I only need to execute an update query if the user don't submit his order before within five minutes, I need a timer (I'm using PHP and MySQL) that is not reset when changing page, some like an $_SESSION, when user add a item in the cart his status on his table be "unavailable" (just to mention something) and the timer begins, and when it reaches zero do a update query and change his state to "available". What interests me most is getting the timer is maintained and not restart when changing page.
I need ideas from you, your suggestions are welcome, Thank you!

You Can store the time-stamp into Mysql table when user adds item to cart, And then create function in a separate php file that checks for time stamps that are expired and updates the status of items that are having expired times,
Now You can either use 'Crons job' to auto check for expired timers or run that function on any user interaction with system as per your needs...!!! :)

Firstly start session and store time stamp both in database and in session when user registers. Then write code that checks last request time is more than 5 mins by subtracting last time stamp with current time. If it's more than 5 mins then change state to available.
Also you can achieve this with MySQL triggers.
http://www.mysqltutorial.org/mysql-triggers.aspx

Related

How to execute some code on a specific datetime to the second?

I'm building a market place with auctions. I need to end auctions preferably at the exact second they are defined to end according to their record in the mysql database.
I know about CRON jobs and I'm currently running a CRON job every minute to execute some script which checks if there are sales that should end.
However this sometimes means that an auction ends almost a minute too late, which is not acceptable. Does anybody know how to make this more accurate without putting a lot of load on the server? For example I wouldn't want to run a script every second to check if sales have ended.
Check timestamp everytime a user try to click auctions button. So even the page haven't refresh and times up, user is not able to bid your item.

How can my session update new changes every time my website is open?

Description:
In my website, there are cash amounts for every person with an account.
By the press of a button, a certain amount of money subtracts or adds from the cash amount.
Problem:
This change only shows in the database (phpmyadmin), but when I write the cash amount on my site, it still shows the old amount. The amount only updates when the user logs out and then back in. I want the amount to automatically update when the page is open.
Question:
Is there a line of code that i can add to my php at the top of the page after session_start(); , such as session_update(); (I know this doesn't exist, it's just an example) or something like that to check for the changes? Or will it have to be a complicated several lines of code? I want to do this without making the person log out.
Thanks for helping! (i'm kind of a noob at this :) )
Let's say you have a session variable of $_SESSION['cash_amount'] and it currently equal $100. If $10 gets subtracted, then in your code, you just say $_SESSION['cash_amount'] -= 10; and it will subtract that from the session variable so next time the user sees the page, it will have the correct amount. Of course you're probably pulling this from the database and if that's the case, then you want that session variable to be equal to the result of the query you're pulling from.
And if you want to do this without refreshing the page, then you'll use AJAX and pull the amount in that way but that's a whole different ball of wax that you might not be prepared for yet.

Browser game PHP+MySQL increasing resource every second

I'm create a small browser game and I'm programming the resource handler.
I'm using PHP and MySQL database.
I realised that I can't update the database every second to increase my resources, so reading on Stackoverflow, I found this post:
I am also trying to make a online game in PHP and encounter also this
problem. My solution was actualy pretty simple. In Assuming you are
using different city's or planets, you will need a database table for
the city/planet. In this database you store the current resources and
the resources per hour. And also a timestamp.
For upgrading resources facility (gold mine for example) i have a
database that has all the building ques with a begin time and end
time.
i then have made a page that i include on every page in the game. It
first checks if there
are any building ques for the selected city that
should be finished since last time database was entered. If that gold
mine was finished at let say 12.00 and the timestamp on your city was
11.00 and current time is 13.00. What the page does, it calculates all the resources for the time 11.00 to 12.00. Then it will update the
gold per hour in the city table. And then it recalculates the
resources from 12.00 to 13.00.
when all the above is done, it puts the timestamp on current. But as
you have all the resources per hour from the second run, you can store
it in an array and let a local timer run to update the resources on
screen. But since you include the above mentioned page on every page,
when you go to the next page it will acces the database to see what
the current resources should be. So the local data is only for
viewing.
By DutchEcho
This is the link: LINK
I programmed the events queue and everything is fine. The problem, now, is to increase the resource if the player is online.
If I save the last_login of the player by time() and then I calculate the new amount of production I have a problem:
"UPDATE `stats` SET `rock` = `rock`+(('".time()."' - $last_login)*$rock_production)
I do: time() - $last_login. If I save the last_login every time a player reloads or changes page, this difference will be always 0.
Because the two times are equal.
How can I increase my resource every second?
Rather than updating last_login on each page load, only update when you start a session. You might have a second field that you update on each page load, and use the difference for your calculation. The two fields could also be used to indicate the duration of the most recent "time on line" even after the user disconnects.
[edit]:
How about using an update trigger? In a single statement you would have both values of last_login available - the new value and the original value.

Tracking how many hours users spend on my website

I am writing a usersystem and as a statistic available for all my users I want to be able to provide them with the amount of hours they've been active on my website.
my original idea as to how to do this was:
user loads a page, and a record for the user is stored in a SQL table called accessLog
*user loads another page, sql query runs to see when they last visited a page*
if the user visited a page within the past two minutes, update their user account and add the time spent online
*insert a new record into accessLog*
however this would mean adding a potential of 4 additional queries to every single page of my website, which seems slow. I was thinking, there has got to be a more efficient way of tracking user activity online that I'm clearly too stupid to see!
My way of doing this is simple:
When a user loads a page, their "last page load time" is updated in the database.
A cron script runs every minute. It looks for users whose "last page load time" was in the last minute.
Increment the "time spent on site" for each user found.
In this way, I can keep track of users accurately to the minute. Just divide by 60 to get the hours.
I would use ajax to get the clients to call the server ever minute or so. Just a to tell the server that the user is still watching that page.
The server would have a lastTimestamp and a totalTimeSpentOnSite in a database. The lastTimestamp would simply have the last time a ajax request or page load occurred.
Every time the ajax fires the server would calculate now - lastTimestamp and add that to the totalTimeSpentOnSite.
To make it even more accurate you could
add javascript listeners to onBlur() to record only the actual time spent with that window active and then send that time to the server instead of just telling the server that the user is still active.
My philosophy is this: don't be overly concerned with efficiency until it becomes a problem. Unless your site has really heavy traffic, you won't notice the four queries. This might be simpler, though:
Log every page load.
Every few hours, run a script through cron that calculates time
spent online for each user and updates a running total in the user
table.
Periodically clear out your access_log table.
Add it to your session management. When a user starts their session record their start time. When the user ends their session record their end time. Simple math from there will gather you the total amount of time they are spending per session on your site.
To answer Filip Haglund
yeah but you'll have to wait for the session to time out, and that time doesn't reflect the actual time the user spent on the last page before he/she closed it.
That's true but then again, all of the answers available so far work on the same basic premise:
Log the page load time.
Log when the user leaves
Update a database table
It just so happens that to log when the user leaves you need sessions. I don't know of any other way in PHP to keep track of user activities the way OP wants. Updating the database table is a technical matter. Do you wanna use a CRON job? Do you wanna use AJAX? Do you wanna do something else?
If you really wanted to know how much activity was actually occurring you could send off AJAX requests for certain JavaScript events. This will tie the time tracking to actual browser events. Of course this means your time tracking relies on JavaScript being enabled.
The "two minute" rule is a little unreliable - and you can get tied up trying to work out what "time spent" actually means.
In a previous project, we did the following.
On each page load, we checked if the user had a current session, and if not, created a GUID to identify the current session.
We wrote a log record to the database with the datetime, GUID, page URL, and user ID (if the user had logged in).
To calculate "time spent", we calculated the time difference between the first and last record for the session GUID, and added one minute to reflect the time spent on the last page.
This is not entirely accurate, but it can run realtime without the need for CRON for sites with moderate amounts of traffic.
first choose a duration beyond which a session is considered interrupted. (ex: 10 minutes)
log all page load with all ip in database
if time between 2 page load for one ip is more than duration don't add this time to the total time for this ip
if time between 2 page load for one ip is less than duration add this time to the total time for this ip
2 problem is :
- if user stay more than duration (10 minutes) in a page without refresh he's considered as disconnected.
- the last page duration is not saved
Piwik works like that
This is what i use and it checks updates the DB anytime the user loads any page.
The data is accurate, as it calculates if the user loads a page per minutes, if so, it adds the time difference to the DB.
$now= time();
$stmt = $db_con->prepare(" SELECT last_seen,time_online FROM user_online_log WHERE user_id=? limit ? ");
$stmt->execute(array( $user_id, 1));
$fetch= $stmt->fetch(PDO::FETCH_ASSOC);
$last_seen=$fetch['last_seen']; //integer value from db, saved from time() function
$last_seen_plus_one_min= $last_seen + 60;
if( $now < $last_seen_plus_one_min ){
$additional_time_online= $now - $last_seen; }
else{ $additional_time_online = 0; }
//update db
$stmt12 = $db_con->prepare(" update user_online_log set last_seen=?, time_online = time_online+? WHERE user_id=? limit 1 ");
$stmt12->execute(array($now, $additional_time_online, $user_id));

How to handle user online status when he/she close the browser?

I am having table to track user online status by setting 'is_online' field to 1. Now User get logged in the site and shut down his/her system or power down at that time he/she logged in.
Here in database 'is_login' has the value '1' which means he is still using the site.
So I have to do some logic to change that value to '0'.
How can i handle this situation using PHP ?
The normal solution is to store a timestamp in the table which you update every time the user does something. Users with a recent timestamp (say, five minutes) are shown as logged in, everybody else are logged out.
It doesn't even have to be updated on every page load. Keep a timestamp in the session with the last update time as well, and only update the table when the database flag are about to expire.
Store an time-since-last-activity. When it's been longer then a specified time - treat as if offline. You should replace the is_online with an DateTime field, and update it every time the logged in user visits the website.
On the place you want to select all online users, instead of :
SELECT * FROM users WHERE is_online = 1
You could use:
SELECT * FROM users WHERE is_online >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
you can't. HTTP closes the connection once the page has been delivered. On the server side alone all you could do is checking if a user has requested a page within a certain amount of time.
JavaScript might be your friend. You could use it to create a ping to a php script which then updates the last request timestamp. Once there is no more pinging, the user is gone and you'd know.
If you have trouble with javaScript, a good point to start would be here: http://www.w3schools.com/JS/
You might want to focus on the AJAX and HTTP request stuff.
cu
Roman
You can use jquery to update your site each X time, so a function is executed each 10 seconds, as following code:
function updateTheBBDD(){
... calling mysql_connect -> mysql_insert -> mysql_close
}
setInterval("updateTheBBDD()",10000);
Also, when painting the user status monitor instead of consulting the BD and:
1->green
0->red
You should:
actual - time > 10 ---> red
actual - time <= 10 ---> green
Due to the stateless nature of the web it is not possible to know exactly when the user left your website. So you can't really trigger any code to change the mentioned value.
As the other have said one has to store the time-since-last-activity to get an approximate idea when was the last time the user was actually doing something with the website.
HTH :)

Categories