【问题标题】:INSERT array into separate rows MySQL将数组插入单独的行 MySQL
【发布时间】:2016-06-16 17:35:27
【问题描述】:

我有一个动态矩阵框,用户可以在其中无限量吸毒,数据是这样通过的:

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

我想要实现的是将每一行插入一个新行(MySQL)并插入到它们的相关列中,如下所示:

:|药物 |实力 |表格 |数量

第 1 行 |卡尔波尔 | 100mg |液体 | 1

Row2 |扑热息痛| 200毫克|平板电脑 | 16

我猜它使用爆炸函数>(我是新手)然后用sql插入字符串?

【问题讨论】:

  • 阅读json_decode
  • 谢谢,我很明白这一点....但是我真的很难将它分成不同的行。

标签: php mysql arrays string exploded


【解决方案1】:

如果您将值作为 json 字符串集合,首先您需要分解字符串,然后使用 for each 循环遍历每个字符串,然后使用另一个 for each 生成单行。请提供以下代码,这可能会对您有所帮助。

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

【讨论】:

  • 太棒了!当我尝试运行它时,这正是我正在寻找的某种原因,它没有插入任何记录?它显示 final_query 但不执行 INSERT
  • @MaxThorley 我没有编写插入代码。您可以使用 mysqli_query() 执行查询并插入记录..:)
猜你喜欢
  • 2011-10-17
  • 1970-01-01
  • 2020-12-31
  • 2016-09-25
  • 2014-06-28
  • 1970-01-01
  • 2014-12-02
  • 2013-10-12
  • 1970-01-01
相关资源
最近更新 更多