2016-03-03 42 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()執行查詢並插入記錄。:) –