Search code examples
phpmysqlarraysstringexploded

INSERT array into separate rows MySQL


I have a dynamic Matrix box where users can unlimited drugs, the data comes through like this:

 [addindividuals] => [{"Drug":"Calpol","Strength":"100mg","Form":"Liquid","Quantity":"1"},{"Drug":"Paracetamol","Strength":"200mg","Form":"Tablet","Quantity":"16"}]

What I'm trying to achieve is to have each line inserted into a new row (MySQL) and inserts into their relevant columns like so:

Columns: | Drug | Strength | Form | Quantity

Row1 | Calpol | 100mg | Liquid | 1

Row2 |Paracetamol | 200mg | Tablet | 16

I'm guessing its using the exploded function> (I'm a novice) and then sql to insert the strings?


Solution

  • If you have the values as a json string collection, First you need to explode then the string then use a for each to loop through each string then use another for each to make single row. Please have a below code this may help you.

    $addindividuals = '{"Drug":"Calpol","Strength":"100mg","Form":"Liquid","Quantity":"1"},{"Drug":"Paracetamol","Strength":"200mg","Form":"Tablet","Quantity":"16"}';
    $exploded_array = explode('},',$addindividuals);
    $final_query = "INSERT INTO `table_name` (`Drug`,`Strength`,`Form`,`Quantity`) VALUES ";
    $exploded_array[0] = $exploded_array[0].'}';
    foreach($exploded_array as $exploded_element)
    {
    $single_row = '(';
    $json_decode = json_decode($exploded_element,true);
    foreach($json_decode as $key => $value)
    {
        $single_row .= "'$value',";
    }
    $single_row = substr($single_row,0,-1);
    $single_row .= '),';
    $final_query .= $single_row;
    }
    $final_query = substr($final_query,0,-1);
    echo $final_query;