codeigniter:如何一次将多个数组值插入mysql数据库?

时间:2015-06-01 17:11:28

标签: php mysql arrays codeigniter

我有一个像这样的数组

array(3) { 
  ["address"] => array(3) { 
     [0] => string(9) "Address 1" 
     [1] => string(9) "Address 2" 
     [2] => string(9) "Address 3" 
  } 
  ["number"] => array(3) { 
     [0] => string(3) "123" 
     [1] => string(3) "456" 
     [2] => string(3) "789" 
  } 
  ["state"] => string(3) "usa" 
} 

我想将数组数据插入到我的数据库表中。所以,我希望我有一个数据数组可以输入这样的数据库

id |  address  |  number  |  state
----------------------------------
1  |  Address 1 |   123    |   usa
2  |  Address 2 |   456    |   usa
3  |  Address 3 |   789    |   usa

如何一次将数组数据插入到数据库表中?我的数组动态,数组的数量可以随时更改。

2 个答案:

答案 0 :(得分:1)

如果使用现有数组

for($i = 0;$i < count($arr["address"]); $i++)
    $this->db->insert('TABLE', 
      array( "address" =>$arr["address"][$i],
             "number" => $arr["number"][$i],
             "state" =>$arr["state"])"); 

或创建新阵列并执行一次批量插入

for($i = 0;$i < count($arr["address"]); $i++)
   $batch[] = array( "address" =>$arr["address"][$i],
             "number" => $arr["number"][$i],
             "state" =>$arr["state"])");
$this->db->insert_batch('TABLE', $batch);

答案 1 :(得分:-1)

只有一种方式: 环

像这样:

$arr=array(1=>5,2=>8,3=>14);//a simple array for example
    for($i=0;$i<$ARRAYMAX;$i++){
        mysql_query("insert into Table1(x) values($arr[$i])");
    }
    $arr =array(3) { 
  ["address"] => array(3) { 
     [0] => string(9) "Address 1" 
     [1] => string(9) "Address 2" 
     [2] => string(9) "Address 3" 
  } 
  ["number"] => array(3) { 
     [0] => string(3) "123" 
     [1] => string(3) "456" 
     [2] => string(3) "789" 
  } 
  ["state"] => string(3) "usa" 
} 


for($i=0;$i<$ARRAYMAX;$i++){

    mysql_query("insert into TABLE(address,number,state)
    values($arr[0][$i],$arr[1][$i],$arr[2][$i])");
}

试试这个,我希望这段代码可以帮助你