2016-03-03 39 views
-2

我有,用户可以无限制的药物,该数据来自通过这样的动态矩阵箱:插件组到单独的行的MySQL

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

我试图做到的,是让每个行插入新行(MySQL)并插入其相关列,如下所示:

:药物|强度|表格|数量

ROW1 | Calpol | 100mg |液体| 1

行2 |扑热息痛| 200mg |平板电脑| 16

我猜使用爆炸功能的>(我是新手),然后SQL插入字符串?

+1

阅读[json_decode(http://php.net/manual/en/function.json-decode.php) – Saty

+0

谢谢你,我很明白....但它得到它在不同的行我真的很挣扎。 –

回答

1

如果你有值作为一个JSON字符串集合,首先你要爆炸,然后再通过串每串用每个循环再使用其他每个进行单列。请有一个下面的代码,这可能会帮助你。

$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; 
+0

太棒了!这正是我正在寻找的原因,当我尝试运行它,它不插入任何记录?它显示final_query但不执行INSERT –

+0

@MaxThorley我没有写的代码用于插入。您可以使用mysqli_query()执行查询并插入记录。:) –