我想在同一ID中设置多个插入复选框。我有这样的表:
id id_fleet unit_id
1 1 CAO27
2 1 CA098
3 2 CA078
以一种形式提交我在id_fleet 1中选择并检查2 unit_id。我尝试使用我的代码只保存一张支票。
这是我在控制器中的代码:
$fleet = $this->input->post('id_fleet');
$unit_id = $this->input->post('unit_id');
$records = array();
for ($i=0; $i < count($unit_id) ; $i++) {
$data = array(
'id_fleet' => $fleet,
'unit_id' => $unit_id
);
array_push($records, $data);
}
$query = $this->database_three->query("select
count(id_fleet_member) as unit from fleet_member
where id_fleet = '$fleet'");
$ans = $query->row();
if ($ans->unit > 0)
{
$this->session->set_flashdata('message', generateErrorMessage('Data gagal ditambah'));
redirect(site_url('fleet_member'));
}
else
{
for ($i=0; $i <sizeof($data['unit_id']) ; $i++) {
$query = "insert into fleet_member (id_fleet, unit_id) values ('".$data['id_fleet']."','".$data['unit_id'][$i]."')";
pg_query($query);
$this->session->set_flashdata('message', generateSuccessMessage('Data berhasil ditambah'));
redirect(site_url('fleet_member'));
}
}
这是我的模特:
function add_fleet_member($data)
{
$this->database_three->insert($this->tbl_fleet_member, $data);
if ($this->database_three->affected_rows() > 1)
{
return true;
}else{
return false;
}
}
这是在视图中:
<div class="checkbox">
<?php foreach ($unit_list as $data) :?>
<label>
<input type="checkbox" name="unit_id[]" value="<?php echo $data->unit_id ?>"><?php echo $data->unit_id ?>
</label>
<?php endforeach?>
</div>
你能帮我解释为什么我的代码只保存一个值复选框吗?
谢谢
答案 0 :(得分:0)
$fleet = $this->input->post('id_fleet');
$unit_id = $this->input->post('unit_id');
//all options are as records in this array
$records = array();
for($i=0;$i<count($unit_id);$i++)
{
//for one record
$data = array(
'id_fleet' => $fleet,
'unit_id' => $unit_id[$i]
);
//push one record to other records
array_push($records,$data);
}
$this->load->model("your_model_name");
//insert multiple records use insert batch active record
$this->your_model_name->add_fleet_member($records);
//model function edited
function add_fleet_member($data=array())
{
if($this->database_three->insert_batch($this->tbl_fleet_member, $data))
{
return true;
}
else
{
return false;
}
}