Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL Update minus variable without separate SELECT Query

Tags:

sql

php

mysql

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.

like image 858
Somk Avatar asked Jun 21 '11 19:06

Somk


2 Answers

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));
like image 67
Michael Berkowski Avatar answered Oct 21 '22 01:10

Michael Berkowski


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
like image 31
webspy Avatar answered Oct 20 '22 23:10

webspy