我是CI的新手。我想用循环向DB添加一些记录。我控制器中的内容是:
$client_name = $this->input->post('client_name');
$contact_person_details = array($this->input->post('contact_person_name_1'),
$this->input->post('contact_person_phone_1'),
$this->input->post('contact_person_email_1'),
$this->input->post('contact_person_name_2'),
$this->input->post('contact_person_phone_2'),
$this->input->post('contact_person_email_2'),
$this->input->post('contact_person_name_3'),
$this->input->post('contact_person_phone_3'),
$this->input->post('contact_person_email_3'),
);
$this->common_model->dbinsert_contactpersons('ci_contact_persons', $contact_person_details, $client_name);
然后在我的模型中:
function dbinsert_contactpersons ($tablename, $details, $client_name) {
for ($i=0; $i<=3; $i++) {
$w = 3*$i;
$j = $w+1;
$k = $w+2;
$insert_detail = array('client' => $client_name,
'contact_person_name' => $details[$w],
'contact_person_phone' => $details[$j],
'contact_person_email' => $details[$k]
);
if($this->db->insert ($tablename, $insert_detail))
{
return true;
}
else
{
return false;
}
}
}
代码将第一个联系人详细信息插入到数据库中(contact_person_name_1,contact_person_phone_1,contact_person_email_1),但不插入其余的...当我var_dump数组$ contact_person_details时,值就在那里。 感谢您的建议...
开始编辑&gt; 我试图优化控制器并摆脱数组,如果有这样的空值:
$contacts_data = array();
for ($i=1; $i<=3; $i++) {
if ($this->input->post('contact_person_name_'.$i) != "") {
$contacts_data['client'] = $this->input->post('client_name');
$contacts_data['contact_person_name'] = $this->input->post('contact_person_name_'.$i);
$contacts_data['contact_person_phone'] = $this->input->post('contact_person_phone_'.$i);
$contacts_data['contact_person_email'] = $this->input->post('contact_person_email_'.$i);
}
}
显然,有错误......有没有正确的方法呢?
答案 0 :(得分:1)
您可以将数组发送到模型并在一行中执行多次插入:
控制器:
$data = array(
array(
'client' => $this->input->post('client_name') ,
'contact_person_name' => $this->input->post('contact_person_name_1') ,
'contact_person_phone' => $this->input->post('contact_person_phone_1'),
'contact_person_email' => $this->input->post('contact_person_email_1'),
),
array(
'client' => $this->input->post('client_name') ,
'contact_person_name' => $this->input->post('contact_person_name_2') ,
'contact_person_phone' => $this->input->post('contact_person_phone_2'),
'contact_person_email' => $this->input->post('contact_person_email_2'),
)
);
$this->common_model->dbinsert_contactpersons('ci_contact_persons', $data);
型号:
function dbinsert_contactpersons ($tablename, $data)
{
$this->db->insert_batch($tablename, $data);
}
您可以使用循环和数组(例如contact_person_name [])优化控制器部分。
更多详情:http://www.codeigniter.com/user_guide/database/active_record.html#insert