0

I am trying to update "new" column value with new value but problem is my query remove previous data while inserting new value

What is want: here is example table structure,

Table name = agg_lvl primary key set = uid

uid     | new
--------|--------
1       | 100
2       | 300

You can see "new" has 100 points, for example I send 100 new points to user 1, so new column value should be 100 + 100 = 200, right now with this code

$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE uid='$uid',new='$new'");

Not sure what

new = '$new'

I have tried both ways but no success = >

new = 'new + $new' or new = new + '$new'
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Goarge Go
  • 57
  • 1
  • 8
  • 2nd: `new=new+$new` exectly = `ON DUPLICATE KEY UPDATE new=new+$new` – splash58 May 01 '16 at 08:27
  • near miss :( so the problem was because of '' i remove it as per your instructions and now able to get my desire results – Goarge Go May 01 '16 at 09:00
  • please post an answer, in comments i have no control to accept your answer, i am asking this because your answer is perfect and credit should gone to where it due, so it's due on you – Goarge Go May 01 '16 at 09:12
  • i am back to computer and writing the answer – splash58 May 01 '16 at 09:55

3 Answers3

2

You should make changes in your query

  1. Make num = nun+$num to add new value to old one
  2. Remove quotes arount $new because it is a number but not a string
  3. Remove uid from set list because insert already point to that record

And your query should look so:

$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE new=new+$new");
splash58
  • 26,043
  • 3
  • 22
  • 34
0

Okay first i will answer with the proper way to do the same, In this case i am assuming that UID is unique, so you make a new table scorecard with UID as foreign key. Now rather than update, you just insert stuff to table like if UID 1 gains 10 and 20 points, there are two entries. onw with 10 and one with 20. Now to get his current points, you add all points where UID=1 .

Now in your implementation the correct query would be

UPDATE userData SET points = points + x WHERE UID = $uid

where x is the new points gained and points is the name of column

georoot
  • 3,557
  • 1
  • 30
  • 59
0

$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new') ON DUPLICATE KEY UPDATE uid='$uid',new=new+$new");

worked for me with help of @splash58

Goarge Go
  • 57
  • 1
  • 8