我有一个由多个复选框和输入字段组成的表单,我想将该数据插入到表的单列中,这是我的表单:
<div id="container">
<h1>property Detail</h1>
<form action="" method="post">
<table>
<tr>
<td>
Possesion
<input type="checkbox" name="feature[]" value="possesion">
</td>
<td>
Possesion1
<input type="checkbox" name="feature" value="possesion1">
</td>
<td>
Possesion2
<input type="checkbox" name="feature" value="possesion2">
</td>
<td>
Possesion3
<input type="checkbox" name="feature" value="possesion3">
</td>
<td>
Possesion4
<input type="checkbox" name="feature" value="possesion4">
</td>
</td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</div>
这是我的 Controller :
function index(){
$this->load->view('form');
if($_POST){
$data_feature = array (
'feature' => $_POST['feature']
);
$data['var']= $this->Mdata->p_detail($data_feature);
}
}
这是我的模型:
function p_detail($data_feature){
$this->db->insert('feature',$data_feature);
return $this->db->insert_id();
}
我在表中只获取一个特征值,我想获取用户选中的复选框的所有值。
问候
最佳答案
最好的保存方法是json_encode,将数据制成json字符串。保存数据的方法有很多,如下所示:
首先更正 html,使所有同名字段都作为数组,如下所示:
<input type="checkbox" name="feature[]" value="possesion">
方法一:
将数据作为 json 字符串保存:
$this->db->insert('feature',json_encode($data));//data is an array need to insert()
方法2:
将数据作为序列化数组:
$this->db->insert('feature',serialize($data));
方法3:
将数据数组设置为字符串:
$this->db->insert('feature',implode(",",$data));
如果您想逐行插入,则在循环中迭代发布的值,如下所示:
function index(){
$this->load->view('form');
if($_POST){
$data_feature = $_POST['feature'];
$data = [];
foreach($data_feature as $f_key => $f_value){
$data[$f_key]['var']= $this->Mdata->p_detail($f_value);
}
}
}
你的模态用法为;
function p_detail($data_feature){
$this->db->insert('feature',$data_feature);//inserts into a single column
return $this->db->insert_id();//returns last inserted id
}
关于php - 如何在codeigniter中的一列中插入多个字段数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42525186/