1

One of my table has a field tags and the value of the field like {2,3,8}

tag_id  | r_tags  
--------|------------   
1       | {2,3,8}  
--------|------------  
2       | {5,8}

I want to update the field without deleting the current value. For ex. If I need to add 5 for tag id 1, then {2,3,8} should be like {2,3,8,5}

Now its works like

 1. Select the current value.
 2. Add 5 using php and created new string.
 3. Update the row.

I just want to know is it possible only through MySql?

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
Nevin Thomas
  • 806
  • 4
  • 12
  • 24

3 Answers3

3

This should work - Assuming you want to add 5 in r_tags in tag_id = 1, this should be the query -

UPDATE tags SET r_tags = CONCAT(SUBSTRING(r_tags, 1, CHAR_LENGTH(r_tags) - 1),',5','}') WHERE tag_id = 1;

In php,

// $new_val and $tag_id as variables.
$query = "UPDATE tags SET r_tags = CONCAT(SUBSTRING(r_tags, 1, CHAR_LENGTH(r_tags) - 1),',$new_val','}') WHERE tag_id = $tag_id"
Kamehameha
  • 5,423
  • 1
  • 23
  • 28
0
UPDATE your_table SET your_field = REPLACE(your_field, '}', concat(',', new_value, '}') WHERE your_field = ?
0

You can try below query for Mysql and you can replace any value with '5' whatever you want to add.

Update tbl_tags SET r_tags = INSERT(r_tags, INSTR(r_tags, '}'), 1, CONCAT(',','5','}')) WHERE tag_id = '1'
Jignesh Patel
  • 1,028
  • 6
  • 10