Jump to content

UPDATE SET with minus


Bradley99

Recommended Posts

Hi,

 

I'm trying to update a table when a form is submitted, so that the column I'm updating is updated by minus one of the values in the form.

Here's my update code:

mysql_query("UPDATE users SET bonusp = 'bonusp-$bonus' WHERE id='$user->id'")
or die (mysql_error());

 

$bonus has a value of either 0 or 1.

 

When i submit with the code i have, it just sets the bonusp in users table to 0.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/264962-update-set-with-minus/
Share on other sites

EDIT: Barand beat me to it, but I'll submit this nonetheless since I included some add'l info.

 

Also, you *could* have done the subtraction in the query. The problem was that you were creating the value as a string by putting quotes around the mathematical expression:

UPDATE users SET bonusp = 'bonusp-$bonus' WHERE id='$user->id'

 

Therefore the value inside the quote marks would be something like '5-2Normally you can put a number inside quotes for input into a numeric field, but it's not really proper. It is only because the MySQL engine can interpret something like '5' as a number. But, if you do any mathematical expression in quotes the MySQL engine cannot resolve that string value into a numeric value. This is no different than how PHP would have handled that:

 

$var1 = '5';
$var2 = '5 - 2'; //This will not be evaluated
$var3 = 5 - 2; //This will be evaluated

echo $var1; // 5
echo $var2; // 5 - 2
echo $var3 // 3

 

So, you could have just changed the query to

[color=#0000BB]mysql_query[/color][color=#007700]([/color][color=#DD0000]"UPDATE users SET bonusp = bonusp-[/color][color=#0000BB]$bonus[/color][color=#DD0000] WHERE id='[/color][color=#0000BB]$user[/color][color=#007700]->[/color][color=#0000BB]id[/color][color=#DD0000]'"[/color][color=#007700])[/color]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.