我想在多个表中添加一些值,但是现在我的代码不是很好。我已将注释掉的值id添加到哪些表中。
控制器名为Add_employee
public function addemp()
{
//id like to add this to 'employees'
$data1 = array(
'emp_no' => $this->input->post('emp_no'),
'birth_date' => $this->input->post('birth_date'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'gender' => $this->input->post('gender'),
'hire_date' => $this->input->post('hire_date'),
);
//idd like to add this to 'titles'
$data2 = array(
'emp_no' => $this->input->post('emp_no'),
'title' => $this->input->post('title')
);
//idd like to add this to 'dept_emp' and id like to add value 'emp_no' to the table 'salaries'
$data3 = array(
'emp_no' => $this->input->post('emp_no'),
'dept' => $this->input->post('dept')
);
$mdata ['m1'] = $data1;
$mdata ['m2'] = $data2;
$mdata ['m3'] = $data3;
$this->add_model->adddata($mdata);
$this->load->view('add_view', $data1);
}
名为Add_model的模型
public function adddata($data) {
//extract();
$this->db->insert('employees', $m1);
$this->db->insert('titles', $m2);
$this->db->insert('dept_emp', $m3);
//$this->db->insert('salaries', $emp_no);//$emp_no => 'emp_no');
return;
}
答案 0 :(得分:1)
你可以试试这个
public function addemp()
{
$data1 = array(...);
$data2 = array(...);
$data3 = array(...);
$mdata['employees'] = $data1;
$mdata['titles'] = $data2;
$mdata['dept_emp'] = $data3;
$this->load->model('add_model'); // If not auto loaded then load it first
if($this->add_model->adddata($mdata))
{
// do something after successful insert
}
else
{
// something went wrong, all not inserted
}
}
public function adddata($data) {
$inserted=0;
foreach($data as $k=>$v) $inserted+=(int)$this->db->insert($k, $data[$k]);
if($inserted===count($data)) return true; // all inserted
return false; // all not inserted
}