I know there is a way to do this. Basically I have the variable $amount
and want to take that away from the column amount in the table stock.
The problem is I normally run a select query find out the value then deduct the variable and run another update query.
What is the syntax to run a single update that will just minus the value.
All help appreciated.
It's as simple as it seems. Parentheses are optional in this example. Be sure to use the appropriate condition in your WHERE
clause!
$qry = "UPDATE table SET column = (column - $amount) WHERE somecondition;";
The variable $amount
is assumed to be properly escaped already, according to the MySQL API you are using, or better yet, a parameter to a prepared example, as in PDO:
$qry = "UPDATE table SET column = (column - :amount) WHERE somecondition;";
$stmt = $db->prepare($qry);
$stmt->execute(array(':amount' => $amount));
Try something like this:
UPDATE table_name SET amount = amount - $amount WHERE primary_key = value LIMIT 1
If you want to make sure amount
doesn't go below zero:
UPDATE table_name SET amount = amount - $amount WHERE primary_key = value AND amount >= $amount LIMIT 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With