我有一个由多个复选框和输入字段组成的表单,我想将该数据插入到表的一个列中,这是我的表单:
<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>
这是我的控制器:
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();
}
我的表中只有一个功能值,我想获取用户选中的复选框的所有值。
此致
答案 0 :(得分:0)
在视图中将所有name="feature"
更改为name="feature[]"
。
最好的方法是将列中的值保存为json
字符串。如下所示。
<强>控制器:强>
function index(){
$this->load->view('form');
if($_POST){
$features = $_POST['feature'];//array of features
$json = json_encode($features);//json string you need to save it in database
$data['var']= $this->Mdata->p_detail($json);
}
}
和
<强>模型强>:
function p_detail($data_feature){
$data = array('feature'=>$data_feature);//sets json string value to feature column
$this->db->insert('feature',$feature);//inserts into a single column
return $this->db->insert_id();//returns last inserted id
}
您需要使用
json_decode()
从array
获取这些值 数据库中。
答案 1 :(得分:0)
保存它的最佳方法是使用json_encode来生成json字符串中的数据。有很多方法可以保存这样的数据:
首先更正html以使所有相同的名称字段与数组相同:
<input type="checkbox" name="feature[]" value="possesion">
方法1:
将您的数据设为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
}
答案 2 :(得分:0)
$feature_array = $_POST['feature'];
$feature_len = count($feature_array);
for ($i=0;$i<$feature_len;$i++) {
p_detail($feature_array[$i]);
}
function p_detail($data_feature) {
$this->db->insert('feature',$data_feature);
return $this->db->insert_id();
}
答案 3 :(得分:0)
您在 Sagar Arora 解决方案中的评论是,您希望将其插入行而不是逗号分隔。 为此,首先您必须将所有复选框名称从name =“feature”更改为name =“feature []”
然后在你的模型中
$this->db->insert_batch('feature', $data_feature['feature']);
答案 4 :(得分:0)
您的应用程序设计存在很大问题,如果您继续这个想法 我认为,更新和删除方法会有另一个问题。
我建议您创建一个功能表,该表可以管理后台应用程序中的所有功能并创建中间表 property_feature 。因为这里功能和属性表之间存在多对多的关系