我想在我的数据库表中使用FK进行多次插入,但只输入一行记录,可能是我不计算$count
。这是我的代码
模型
public function create($table,$data)
{
$query = $this->db->insert($table, $data);
return $this->db->insert_id();
}
控制器
public function save($id)
{
$id_form = $id;
$id_interversion = $this->model->create('mytable1',$data);
$Inicio = $_POST['Inicio'];
$Termino = $_POST['Termino'];
$id_tecnico = $_POST['id_tecnico'];
$count = count($_POST['id_tecnico']);
$data2 =array();
for ($i=0; $i <$count; $i++) {
$data2 = array(
'id_tecnico'=>$id_tecnico[$i],
'horaInicio'=>$Inicio[$i],
'Termino'=>$Termino[$i]
);
$this->model->create('mytable2',$data2);
}
}
视图
<?php echo form_open("controller/save/{$data->id}"); ?>
<?php for ($i=0; $i <2; $i++) { ?>
<input type="text" name="id_tecnico[]" value="" class="form-control">
<input type="text" name="Inicio[]" value="" class="form-control">
<input type="text" name="Termino[]" value="" class="form-control">
<?php } ?>
<?php echo form_close(); ?>
我希望我解释好问候
答案 0 :(得分:1)
尝试insert_batch
这样:
public function save($id = NULL)
{
$id_form = $id;
//$id_interversion = $this->model->create('mytable1',$data);
$id_interversion = 12; // a custom id
$Inicio = $this->input->post('Inicio');
$Termino = $this->input->post('Termino');
$id_tecnico = $this->input->post('id_tecnico');
foreach ($id_tecnico as $key => $item)
{
$insert_data[] = array(
'id_interversion' => $id_interversion,
'id_tecnico'=> $item,
'horaInicio'=> $Inicio[$key],
'Termino'=> $Termino[$key]
);
}
//print_r($insert_data);die;
$this->db->insert_batch('mytable2',$insert_data);
}
答案 1 :(得分:0)
您可以将插入值组合到一个数组中,并使用codeigniter insert_batch方法。
此处提供了有用的文档 https://www.codeigniter.com/userguide3/database/query_builder.html