dongmo3413 2014-12-14 12:18
浏览 489
已采纳

如何将数组中的每个数据保存到数据库中

array of data

I have a form where I needed to split into two table in the database. tbl_1 consist of single value per column, then tbl_2 consist of multiple value per column. I know if I pass multiple data per column I'm going to violate a normalization in database. So what I did I reference tbl_1 to tbl_2. The problem is I don't know how to save each value in an array to a column. example Classification has 4 value which I needed to save in tbl_2 and reference it to tbl_1. How am I able to do this? I'm using PDO.

HTML snippet:

<input type="text" name="classification[]" placeholder="Classification No. 1" />
<input type="text" name="classification[]" placeholder="Classification No. 2" />
<input type="text" name="classification[]" placeholder="Classification No. 3" />
<input type="text" name="classification[]" placeholder="Classification No. 4" />

So for each value will create 4 rows that has the same id being reference to tbl_1. It should be like this:

enter image description here

  • 写回答

2条回答 默认 最新

  • duanshang7007 2014-12-14 13:30
    关注

    Try multidimensional array instead.

    So, you input can be something like:

    <input type="text" name="data[classification][]" placeholder="Classification No. 1" />
    <input type="text" name="data[area][]" placeholder="Area No. 1" />
    <input type="text" name="data[market_value]" placeholder="Market Value No. 1" />
    

    Then, using for loop, you can insert them to database:

     $data = 'your array here whatever you receive using GET/POST';
    
    for($i=0; $i<count($data['classification']); $i++){
      $sql = INSERT INTO (`tbl_1_id`, `tbl_2_id`, `classification`, `area`, `market_value`) VALUES (`auto_increment_id`, `value_of_table1`, $data['classification'][$i], $data['area'][$i], $data['market_value'][$i]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器