简体   繁体   中英

Insert data into multiple tables from single form submit

I have the form as mentioned below.

and getting the following output.

Help me to get the output as following with foreach loop.

array('notification') = array('pos_id' => 'kiran','post_usr' => 'kumar','comment' => 'kaleti');
array('project') = array('Project_name' => 'india','Proejct_lang' => 'hyderabad');

Here is controller code.

// controller
public function form_submit() { 
  $total_data = $this->input->post(); 
  print_r($total_data);
  //output :Array ( [notification|pos_id] => kiran [notification|post_usr] => kumar [notification|comment] => kaleti [project|Project_name] => india [project|Proejct_lang] => hyderabad )
  foreach ( $total_data as $key => $value ) { 
    $arr = explode("|",$key); 
    echo $arr[0]."--".$arr[1]."--".$value."<br />"; 
  }
}

Here is controller code you will get data from VIEW as input fields of view that you will collect in controller .

// Controller
$data_array1 = array(
    'table_field_name_here' => $this->input->post('pos_id'),
    'table_field_name_here' => $this->input->post('post_usr'),
    'table_field_name_here' => $this->input->post('comment'),
);

$data_array2 = array(
    'table_field_name_here' => $this->input->post('Project_name'),
    'table_field_name_here' => $this->input->post('Proejct_lang'),
);  

$table_1 = 'table_name';
$table_2 = 'table_name';
$record_id_1 = $this->Common_model->insert_into_table($table_1, $data_array1);
$record_id_2 = $this->Common_model->insert_into_table($table_2, $data_array2);
if($record_id_1 && $record_id_2){
    // success ...!
}else{
    // fail ...!    
}

The model function which you will call from your controller.

// Model
function insert_into_table($table, $data) {
    // echo "<pre>asdf";print_r($data);exit;
    $insert = $this->db->insert($table, $data);
    $insert_id = $this->db->insert_id();
    if ($insert) {
        return $insert_id;
    } else {
        return false;
    }
}

Hope you will get the idea how simple to insert data into two tables using model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM