Hey guys I am trying to make a counter that count for 10 min form that last time user pressed the button(for ex requested anything).
What I did, I took timestamp in Mysql and code is below.
$timequery =" SELECT NOW() AS cur, ( SELECT lastclaim FROM table1 WHERE id =".$id." ) AS mytime ";
if( $qry=mysql_query( $timequery ) )
{
$timer1 =strtotime( mysql_result($qry, 0,'mytime'));
$timer2 =strtotime( mysql_result($qry, 0,'cur'));
$timer = abs( $timer2 - $timer1);
return $timer;
}
Please suggest me better logic for this problem or guide me for improve this code.
IMUO i wouldn't go to ask at database, you could do it with SESSIONs and you will have less DB access. I.E you coud do something like:
$nowtime = date('Y-m-d h:i:s');
if(isset($_SESSION['timeOfLastAction']){
$timeOfLastAction = $_SESSION['timeOfLastAction'];
}else{
$timeOfLastAction = $nowtime;
}
$endtime = strtotime( $timeOfLastAction ) + 600; // 10 minutes == 600 seconds
if($nowtime > $endtime){ //10 min or more from last action
//do your stuff
$_SESSION['timeOfLastAction'] = date('Y-m-d h:i:s'); //reassing
}
If you need/want to store at database you could change the if{}else{}
part to your actual code.. but you have to access to database, store value, update the value in each request, etc. you could use a mysql native function like:
SELECT * FROM table1
WHERE lastclaim <= NOW() - INTERVAL 10 MINUTE
AND id=$id
And you will avoid the data manipulation in PHP, you will recive a user
only if the interval is >10 min.
Here a similar issue of yours: Adding 10 minutes to a date from mysql datetime and comparing it to the time now
I hope it helps!