Ben
Ben

Reputation: 369

PHP/MySQL update mysql field after 10 minutes has elapsed.

As the title reads, I am looking for a way to update a mysql field after 10 minutes has elapsed of a query being run.

Something like below is an example without the time restraint:

mysql_query("UPDATE `players` SET `playcoins`=TRUNCATE(ROUND((`playcoins`+$amount),9),8) WHERE `id`=$player[id] LIMIT 1"); 

Any ideas?

Upvotes: 1

Views: 563

Answers (2)

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

You go it the wrong way. Sure you can do it. And you can do it with PHP. But you shouldn't. PHP is not the right language to do such a task. Before I starting talk about shell_execute and sleep, which would be the core elements, you need to do this, I offer you another solution.

If I see right, you want to give a player every 10 minutes, some coins.

The right approach would´basicly be:

Save the last time the player has get coins in the database. If you get the player coins, you first want to check, the last time you give the player coins. Now calculate, how much he has earned in this time difference. Finaly add this to his balance and update the field, where you save the last time, the player has earned coins.

An alternative would be a Cronjob/Scheduled Task to a PHP file, which is called every 10 minutes, to give each player the coins, he should get.

Upvotes: 1

O. Jones
O. Jones

Reputation: 108851

MySQL databases have a class of object called an EVENT. It's basically a hunk of SQL code that runs at particular time, or on a particular interval.

You could use code like this to create an event to do what you require at the right time in history. This particular code will create an event that runs just once, ten minutes in the future.

DELIMITER $$
DROP EVENT IF EXISTS coins_user12345$$
CREATE EVENT coins_user12345
    ON SCHEDULE
        AT NOW() + INTERVAL 10 MINUTE
    ON COMPLETION NOT PRESERVE
    ENABLE
DO BEGIN
    UPDATE players 
       SET playcoins=TRUNCATE(ROUND((playcoins+123),9),8) 
     WHERE id=12345
     LIMIT 1;
END$$
DELIMITER ;

To use these EVENT objects, you have to configure the event scheduler correctly. Read this. http://dev.mysql.com/doc/refman/5.6/en/events-configuration.html Some cheap shared hosting providers don't allow the use of events, so this is not guaranteed to work.

Upvotes: 1

Related Questions