Decrement value in mysql but not negative
I want to decrement a value when user delete it in php and mysql. I want to check not to go below than 0. If value is 0 then do not decrement.
mysql_query("UPDATE table SET field = field - 1 WHERE id = $number");
If field is 0 then do not do anything
Solution 1:
Add another condition to update only if the field
is greater 0
UPDATE table
SET field = field - 1
WHERE id = $number
and field > 0
Solution 2:
You could prevent the new value to drop below zero by using GREATEST()
. If the value drops below zero, zero will always be greater than your calculated value, thus preventing any value below zero to be used.
UPDATE table
SET field = GREATEST(0, field - 1)
WHERE id = $number
And on a side note: Please don't use mysql_*
functions any more. They are deprecated and will eventually be removed from PHP. Use PDO or MySQLi instead.
Solution 3:
The option using GREATEST will not work in newer MySQL versions, and the accepted answer can be unuseful if you want to update multiple fields instead of one. My solution for this problem is using IF:
UPDATE table
SET field = IF(field > 0, field - 1, 0)
WHERE id = $number