usersubuser
usersubuser

Reputation: 117

queue if php update mysql each minute

I'm trying to do something that will execute 3 different things on different times.

So the first minute will do a mysql query update an set server to 1.

Second minute will update and set the server row to 2.

Third minute will update and set the server row to 3

Then fourth minute will update and set the server row again to 1.

Fifth minute will update and set the server row again to 2.

Sixth minute will update and set the server row again to 3 and so on but always 1,2,3 1,2,3.

I could do something like this but then I have a very long code and I know it's possible to do it shorter but can't figure how.

$t_Min=date("i");

if ($t_Min == 1) {
mysql_query("UPDATE `list` SET `server` = '1'"); }

else if ($t_Min == 2) {
mysql_query("UPDATE `list` SET `server` = '2'"); }

else if ($t_Min == 3) {
mysql_query("UPDATE `list` SET `server` = '3'"); }

else if ($t_Min == 4) {
mysql_query("UPDATE `list` SET `server` = '1'"); }

else if ($t_Min == 5) {
mysql_query("UPDATE `list` SET `server` = '2'"); }

else if ($t_Min == 6) {
mysql_query("UPDATE `list` SET `server` = '3'"); }

Upvotes: 0

Views: 136

Answers (2)

Robbie
Robbie

Reputation: 17720

Easiest to let SQL do the work - in one query:

UPDATE list SET server=IF(MOD(MINUTE(NOW()), 3) = 0, 3, MOD(MINUTE(NOW()), 3))

This relies on the timestamp in MySQL being right, of course. You could also use variable to store the MOD, but this reads easily enough.


Edit: of course, if you want the number in PHP, you can do the math there. Broken down step by step would be:

$t_Min = (int)date("i");
$minuteMod = $t_Min % 3;  // This is modulus
$minutes = ($minuteMod == 0 ? 3 : $minuteMod);

Upvotes: 3

Paul Spiegel
Paul Spiegel

Reputation: 31812

Use the modulo operator %:

$insertValue = ($t_Min-1) % 3 + 1;

Here is a demonstration:

$values = [1,2,3,4,5,6];

foreach ($values as $t_Min) {
    $insertValue = ($t_Min-1) % 3 + 1;
    echo "$t_Min => $insertValue \n";
}

Will return:

1 => 1 
2 => 2 
3 => 3 
4 => 1 
5 => 2 
6 => 3

Demo: http://rextester.com/FOH77937

Upvotes: 0

Related Questions