2

How do i update and copy data from the same table but the new data is JSON formatted data.

I am expecting the updated field to be: {"t":"token1", "s":"secret1"}

DB user_api table:

(id) (token) (secret) (api)
---------------------------
 1   token1  secret1  NULL

Update query:

UPDATE user_api SET api = '{"t":"' +token+ '", "s":"' +secret+ '"}';
4
  • 1
    sidenote: you realize that without a WHERE clause, it will update your entire table. Not a problem if you only have or will always have the one row. Commented May 6, 2016 at 12:19
  • 1
    MySQL treats + as an addition operator; but has a CONCAT() function that allows you to concatenate strings Commented May 6, 2016 at 12:21
  • From a database design prespective: It does not make much sense to concatenate 2 columns into a third column. If some part of your App needs this done, then do it in the PHP when you present or make some use of this concatenation. Commented May 6, 2016 at 12:34
  • @RiggsFolly thanks for the input. This is only to update existing records. Commented May 6, 2016 at 13:02

2 Answers 2

4

Use CONCAT

UPDATE user_api SET api = CONCAT('{"t":"', token, '", "s":"', secret, '"}');
Sign up to request clarification or add additional context in comments.

Comments

0

Use JSON_SET() function instead.

UPDATE `user_api` SET `api` = JSON_SET(`api`,'$.t',token,'$.s',secret) WHERE ...

This helps you to get rid of all the CONCAT stuff. JSON_SET() function insert the key/value pair if the key is not exists in the specified field. If it exists, then the function update the value.

You can use JSON_INSERT() function if you want to insert if the key doesn't exists. Or you can use JSON_REPLACE() function if you want just update the value if the key exists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.