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 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问