简体   繁体   中英

Inserting multiple rows in database codeigniter

I have some issue about the inserting data. It will insert only the waybillno data but the quantity is always same. Please check my code - I think the model is wrong.

Controller

public function create_cargo_manifest(){
   $core_model = new Core_m;
   $core_model->save_cargo_details($this->input->post());
   redirect('core/cargo_lookup/');
}

Model

function save_cargo_details(){

$quantity =  $this->input->post('quantity');
$waybilldate =  $this->input->post('waybilldate');

$data = array();
foreach($this->input->post('sys_wbdetails') as $sys_wbdetails) {
$data[] = array(
        'waybillno' => $sys_wbdetails,
        'quantity' => $quantity,
        'waybilldate' => $waybilldate,
       );
 }

   return $this->db->insert_batch('sys_cargodetails', $data); 
}

View

<?php foreach($waybill_header as $waybill_header) { ?>
  <?php echo form_open('core/create_cargo_manifest'); ?>
    <td><input type="checkbox" name="sys_wbdetails[]" value="<?php echo $waybill_header->waybillno; ?>"></td>
    <td><?php echo $waybill_header->waybillno; ?></td>
    <td><?php echo $waybill_header->waybilldate; ?><input type="hidden" value="<?php echo $waybill_header->waybilldate; ?>" name="waybilldate"></td>
    <td><input type="text" size="5" value="<?php echo $waybill_header->quantity; ?>" name="quantity"></td>
    <td><input type="submit" value="save"></td>
  <?php } ?>
<?php form_close(); ?>

All your inputs for quantity have the same name : quantity . So you're only submitting the last value in your form. You need to use an array for those inputs ( quantity[] ), just like for your checkboxes. And you might want to do the same for the waybilldate inputs.

<td><input type="text" size="5" value="<?php echo $waybill_header->quantity; ?>" name="quantity[]"></td>

And then in PHP, something like that :

$data = array();
// Count distinct entries in the form
$count = count($this->input->post['sys_wbdetails']);

for($i=0; $i < $count; $i++) {
    $data[] = array(
        'waybillno' => $this->input->post['sys_wbdetails'][$i],
        'quantity' => $this->input->post['quantity'][$i],
        'waybilldate' => $this->input->post['waybilldate'][$i],
       );
}

EDIT : also, take a look at this answer if you want a clean way to keep track of which form input goes where.

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