我想使用Codeigniter从checkbox [array]将数据插入数据库。 我的情况是用户检查asogramsmen标准基础从复选框表格,然后我的控制器处理复选框时检查然后值为1,如果取消选中然后是0.这是我的观点
ID | Trimester I | Trimester II | Trimester III |
21 | checbox_trimester_i[] | checbox_trimester_ii[] | checbox_trimester_iii[]
42 | checbox_trimester_i[] | checbox_trimester_ii[] | checbox_trimester_iii[]
23 | checbox_trimester_i[] | checbox_trimester_ii[] | checbox_trimester_iii[]
我想插入表'assesmen'。这是我在DB
中的专栏ID | ID_pk | Trimester_1 | Trimester_2 | Trimester_3 |
1 | 21 | 1 | 0 | 1
2 | 42 | 0 | 1 | 1
3 | 23 | 1 | 0 | 0
注意*:
ID_pk = ID
Trimester_1 => checbox_trimester_i[]
Trimester_2 => checbox_trimester_ii[]
Trimester_3 => checbox_trimester_iii[]
以下是我的查看表单:
foreach ($kuisioner as $art) { $no++; ?>
<tr>
<td><input type="hidden" name="id[]" value="<?php echo $art->id ?>"></td>
<td align="center">
<input type="checkbox" name="checbox_trimester_i[]">
</td>
<td align="center">
<input type="checkbox" name="checbox_trimester_ii[]">
</td>
<td align="center">
<input type="checkbox" name="checbox_trimester_iii[]">
</td>
</tr>
<?php }
这是我的控制器,但仍然无法正常工作,请帮我解决。谢谢
$posted = $this->input->post();
$as_trim_satu = isset($posted['checbox_trimester_i']) ? $posted['checbox_trimester_i'] : array();
$data = array();
foreach($posted['id'] as $key => $value)
{
$info_user = array(
'user_id' => $value,
'trimester_satu' => in_array($posted['id'][$key], $as_trim_satu) ?1:0,
);
$data[] = $info_user;
}
echo "<pre>";
print_r($data);
echo "</pre>";
答案 0 :(得分:1)
您可能需要像下面一样调整视图,以便在控制器中获得正确的值。如果是这样,您可以使用以下代码。
给出复选框的名称,如
name="checbox_trimester_i[<?php echo $art->id ?>]"
查看我更新的视图。
<?php foreach ($kuisioner as $art) { $no++; ?>
<tr>
<td><input type="hidden" name="id[]" value="<?php echo $art->id ?>"> </td>
<td align="center">
<input type="checkbox" name="checbox_trimester_i[<?php echo $art->id ?>]" value="1">
</td>
<td align="center">
<input type="checkbox" name="checbox_trimester_ii[<?php echo $art->id ?>]" value="1">
</td>
<td align="center">
<input type="checkbox" name="checbox_trimester_iii[<?php echo $art->id ?>]" value="1">
</td>
</tr>
<?php } ?>
以下是访问从页面
发布的表单数据的控制器代码if($this->input->post()){
$data = array();
$ids = $this->input->post('id');
$checbox_trimester_i = $this->input->post('checbox_trimester_i');
$checbox_trimester_ii = $this->input->post('checbox_trimester_ii');
$checbox_trimester_iii = $this->input->post('checbox_trimester_iii');
if($ids ){
foreach ($ids as $key => $value){
$info_user = array(
'user_id' => $value,
'Trimester_1' => !empty($checbox_trimester_i[$value]) ? 1: 0,
'Trimester_2' => !empty($checbox_trimester_ii[$value]) ? 1: 0,
'Trimester_3' => !empty($checbox_trimester_iii[$value]) ? 1: 0,
);
$data[] = $info_user;
}
}
echo "<pre>";
print_r($data);
echo "</pre>";
}
请注意我创建的变量$info_user
。您可以在更新之前使用正确的数据库列名称。