简体   繁体   中英

MySQL Query form data

I have a php form that when submitted sends form values into a MySQL Database named "Hotel" in a table named "Reservations" that has one column titled "Form". In the "Form" column, each form field is enclosed within {} and fields are separated by commas. Here is what the data looks like in the "Form" column:

[{"id":"1","translation":"Token","value":"123456789"},
 {"id":"2","translation":"Name","value":"John Smith"}]

Desired MySQL Query Result: I want to grab each "translation" and "value" in my query and have them put into separate columns. Column 1 title "Token", Column 2 title "Name" then list the values below each

--------------------------
| Token     | Name       |
--------------------------
| 123456789 | John Smith |
--------------------------

I have never run into this kind of data in a column before so I am unsure how to create the query. I'm thinking substring perhaps? Any help or guidance is greatly appreciated. Please let me know if more information is need from me to help process the request.

The form column has data format in json. Simply fetch the column value and use php function $result = json_decode(data); Now $result holds the data in array format. Use for each to iterate the array and fetch each value.

First, let's take the JSON string that's in the Form column and turn it into an array with json_decode() . Assuming you've already retrieved the value from the Form column and assigned it to the variable $form :

$form = json_decode($form,true);

Next, we'll retrieve the Token value and the Name value:

$token = $form[0]["value"];
$name = $form[1]["value"];

Note: This assumes that 'token' always occurs first in the 'form' string, and that 'name' always occurs second.

You can it do like this:

Samples to get the Values:

SELECT REGEXP_REPLACE('[{"id":"1","translation":"Token","value":"123456789"},{"id":"2","translation":"Name","value":"John Smith"}]',
                      '^.*"translation":"Token","value\":"([0-9]+)".*$','\\1') AS Token;

RESULT: 123456789

SELECT REGEXP_REPLACE('[{"id":"1","translation":"Token","value":"123456789"},{"id":"2","translation":"Name","value":"John Smith"}]',
                      '^.*"translation":"Name","value\":"(.*)".*$','\\1') AS Name;

RESULT: John Smith

To Update the Table:

update TABLENAME set
  TOKENFIELD = REGEXP_REPLACE(JSONFIELD,{"id":"2","translation":"Name","value":"John Smith"}]',
                          '^.*"translation":"Token","value\":"([0-9]+)".*$','\\1'),
  NAMEFIELD = SELECT REGEXP_REPLACE(JSONFIELD,{"id":"2","translation":"Name","value":"John Smith"}]',
                          '^.*"translation":"Name","value\":"(.*)".*$','\\1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM