将输入字段作为数组插入,将其值插入表中

时间:2014-02-27 12:55:13

标签: php codeigniter

我有一个简单的查询,为我制造麻烦.. 我需要插入基本上包含2个输入字段的表单

<input type="text" name="slottiming[]" value="" ></input>
<input type="text" name="slottname[]" value=""></input>

。 。 。 ..       

和我一样,我创建了48个输入字段(对)来存储在我的表中的2个字段中

|id | Timing | Slotname
| 1 | 00:00  | 4
|   |        |

这是我的控制器::

$slotname=$this->input->post('slotname');
        $slot=$this->input->post('slot');

            print_r($slotname);

        foreach($slotname as $key =>$slot)
        {
                $form_data=array(
                'slottime'=>$slotname,
                'seat' =>$key,
                'assocviva' => 'Cycle1'
                );
            $this->load->model('modelquery');
            $this->modelquery->common_add($table_name,$form_data);

        }

如何将insert into common_add方法的正确查询写为$form_data参数arry with field

3 个答案:

答案 0 :(得分:0)

你正在寻找以下答案吗?

function common_add($ table_name,$ form_data)
{
$ this-&gt; db-&gt; insert($ table_name,$ form_data);
}

查看http://ellislab.com/codeigniter/user-guide/database/active_record.html

中的数据库插入文档

希望它有用

答案 1 :(得分:0)

如果我理解正确,$ slotname是您要存储的数组?

一个快速解决方法是在将数组插入数据库之前序列化数组,并在从数据库中检索数组时进行反序列化。

$form_data=array(
    'slottime' => serialize($slotname),
    'seat' => $key,
    'assocviva' => 'Cycle1'
);

然后从数据库中获取

$slotname = unserialize($row->slotname);

答案 2 :(得分:0)

我不会在这里使用foreach。因为它们是成对的,所以你应该使用for循环来结合相同的结果。

$this->load->model('modelquery');
$slotname = $this->input->post('slotname');
$slot     = $this->input->post('slot');

for ($i=0; $i < count($slotname); $i++){
 $form_data = array(
  'slottime' => $slotname[$i],
  'seat'     => $slot[$i],
  'assocviva'=> 'Cycle1'
 );
 $this->modelquery->common_add($table_name, $form_data);
}

永远不要将模型加载线放在循环中。