Reputation: 8282
I'm using the following to restrict an IP to send 1 message per 5minutes. So I want to echo time remaining, how do I calculate that?
Here's my PHP
$query = "SELECT * FROM messages WHERE ip = '$ip' AND mtime >= NOW() - INTERVAL 5 MINUTE";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo "<script>
alert ('You can only send 5 message every 10min. please wait.')
</script>";
} else {
}
Upvotes: 1
Views: 1384
Reputation: 1225
If you mtime column contain microtime value, you can do it like that:
$query = "SELECT * FROM messages WHERE ip = '$ip' AND mtime >= NOW() - INTERVAL 5 MINUTE ORDER by mtime DESC";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$diff = microtime(true) - $row['mtime']; //here the time difference between last sended message and this try
$remaining = (5*60 - (int) $diff);
...
}
else {
...
}
I also change the query order in order to get difference between now and the last message. If you need later to check for 5 messages per time, you need to remove that order.
You can use time function, if microtime isn't working:
$diff = time() - $row['mtime'];
Upvotes: 3
Reputation: 9635
get current time first like this in timestamp
$c_time = strtotime(date('d-M-Y g:i:s'));
now get time past 5 minute like this
$l_time = $c_time-(5*60);
now put your query
$query = "SELECT * FROM messages WHERE ip = '$ip' AND mtime >= '$l_time' ORDER by mtime DESC";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$remaining_time = $c_time - $row['mtime']; // this will be remaining time in seconds use it accordingly
...
}
else {
...
}
i hope you will find your answer
Upvotes: 0