Php-在Ci中插入多行
我有一个数组['abc','xyz'] 我想一次插入两行 我不想要Php-在Ci中插入多行,php,codeigniter,Php,Codeigniter,我有一个数组['abc','xyz'] 我想一次插入两行 我不想要 loop(){ $this->db->insert() } 这将运行两次insery查询 使用CI框架 这个数组来自用户yourModel.php public function urfunctionName($data) { foreach($data as $res) { $this->db->insert('table_name',$res); } } 希望对你有用 您
loop(){
$this->db->insert()
}
这将运行两次insery查询
使用CI框架
这个数组来自用户yourModel.php
public function urfunctionName($data)
{
foreach($data as $res)
{
$this->db->insert('table_name',$res);
}
}
希望对你有用
您需要首先构建“批处理”插入查询。然后调用
insert\u batch
方法
$array = ['abc','xyz'];
$batchInsertArray = buildBatchInsertArray($array);
$this->db->insert_batch('myTable', $batchInsertArray);
function buildBatchInsertArray(array $array): array
{
$batchInsertArray = [];
foreach ($array as $item) {
$batchInsertArray[] = [
'columnName' => $item
];
}
return $batchInsertArray;
}
参考::您使用的是什么DB控制器?@WKoppel使用CI Frameworkinside循环写入插入query@Daan这是一本从数组输入中获取值的手册我能做什么?在询问之前请阅读手册,我在谷歌上10秒钟内就发现了这一点:
insert_batch
我告诉过你不要在loopShow中这样做,告诉我你的预期结果我会得到相同的结果,但你的代码会运行与我的数组长度相等的查询,就像数组有100个索引一样,它会运行100次,这不好。我想在一次运行中插入100行,谢谢你的帮助insert_batch()谢谢大家。你想解释一下代码,让OP决定为什么他需要将代码更新到这个版本。谢谢你的回答。请为您的代码示例提供一些说明。
foreach ($this->input->post("name") as $value) {
$name[] = array(
'name'=>$value,
);
}
$this->db->insert_batch("names",$name);
$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')