I have a database of a number of purchased plans with a value of minutes_left from which I want to subtract 1 number every minute.
Now I am using this code using cron job:
$sql = "SELECT * FROM pls";
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$theM = $row['minutes_left'];
$realM = intval($theM) - 1;
$sqlE = "UPDATE pls SET minutes_left=?";
$stmtE = $pdo->prepare($sqlE);
$stmtE->execute([strval($realM)]);
}
But for example, if there are 27 minutes from one, and 12 minutes from another, and 15 minutes from another, all of them will change to 26, 25, etc., and each of them will not reduce theirs.
2
Answers
UPDATE pls SET minutes_left=?
should be something likeUPDATE pls SET minutes_left=minutes_left-?
or evenUPDATE pls SET minutes_left=minutes_left-1 where minutes_left > 0
Meaning, you don’t want updateminutes left
to a literal value, but instead you want to updateminutes_left
to subtract the next minute from it – a calculated value.But consider setting something like a start time and minutes or an expiration time and then you could just check if expiration time is exceeded without constant updates (this is the same concept as birthdays – do you save Age in your database, or do you save BirthDate in your database. Age is always changing, but BirthDate is a constant you can use to calculate Age.
There is no need to query them first and then update. You can do the update in a single step.
If you don’t want to go below 0 you can use a max function called GREATEST().
or suggested by @topsail to decrease only those which are greater than 0.