How to insert and update multiple selected values with codeigniter?

how to insert multiple select values in database in codeigniter
how to update dropdown value in codeigniter
how to insert multiple array values into database codeigniter
update query in codeigniter using where condition
insert query in codeigniter example
codeigniter dropdown selected value
how to edit multiple select box in codeigniter
insert update delete in codeigniter

So I have a problem with many to many relationships. Currently, I have surat and surat_user table. How do I insert data into surat and at the same time insert multiple values from select2 multiple forms into surat_user table and how to get data so I can update it.

UPDATE : I solve the insert problem please see answer below

But now i have no idea how to update those values. For example

surat_user

id_surat | id_user
    1    |  1
    1    |  2

How to update surat_user (in controller and model) if i want to remove one of id_user where 'id_surat = 1`

At the moment i don't know how to fetch the multiple values into select2 form edit so here is mu uncomplete codes :

Controller

public function edit_sm($id_surat){
    $this->load->view('template/header');       
    $this->load->view('template/sidebar');
    $where = array('id_surat' => $id_surat);
    //$data=array('id_status'=> $this->M_sm->get_option()); 
    $data['surat'] = $this->M_sm->edit_sm($where,'surat')->result();
    $this->load->view('v_edit_surat',$data);
    $this->load->view('template/footer');
}

public function edit_sm_proses() {
    $data = array(
        'id_surat'=>$this->input->post('id_surat'),
        'no_surat'=>$this->input->post('no_surat'),
        'id_status'=>$this->input->post('id_status'),
        'id_user'=>$this->input->post('id_user')
        );
    $where = array(
    'id_surat' => $id_surat
);

    $this->M_sm->edit_sm_proses($where,$data,'surat');
    redirect('SuratMasuk');
}

Model:

public function edit_sm($where,$table){     
    $this->db->join('status_surat', 'status_surat.id_status = surat.id_status');
    return $this->db->get_where($table,$where);
}

public function edit_sm_proses($where,$data,$table){
    $this->db->where($where);
    $this->db->update($table,$data);
}

View

<section class="content">
    <div class="row">
      <div class="col-xs-12">
        <div class="box box-solid box-primary"">
          <div class="box-header with-border">
          <h3 class="box-title">Default Box Example</h3>
          </div>
          <!-- /.box-header -->
          <div class="box-body">
            <?php foreach ($surat as $key) { ?>
            <form method="post" action="<?php echo base_url()."SuratMasuk/edit_sm_proses" ?>" enctype="multipart/form-data" />
            <input type="hidden" name="id_surat" value="<?=$key->id_surat?>">


        <div class="form-group">
          <label class="control-label col-lg-2">No Surat</label>
          <div class="col-lg-5">
            <input type="text" name="no_surat" class="form-control no_surat" placeholder="Masukkan Nomor Surat" value="<?=$key->no_surat?>">
            <span class="help-block"></span>
          </div>
        </div>
        <br>
        <br>
        <div class="form-body">
        <div class="form-group">
          <label class="control-label col-lg-2">Status</label>
          <div class="col-lg-5">
            <select class="form-control select2 id_status" name="id_status" style="width: 100%;">
                <option value="<?=$key->id_status;?>" selected="<?=$key->id_status;?>"><?php echo $key->status;?></option>
                <?php foreach ($id_status as $row) { ?>
                <option value="<?php echo $row->id_status; ?>"> <?php echo $row->status; ?></option>

                <?php } ?>
                </select>
           <span class="help-block"></span>
          </div>
        </div>
      </div>
      <br>
      <br>
      <div class="form-body">
        <div class="form-group">
          <label class="control-label col-lg-2">Disposisi</label>
          <div class="col-lg-5">
            <select class="form-control select2 id_user" name="id_user[]" style="width: 100%;">
                <option value="<?=$key->id_user;?>" selected="<?=$key->id_user;?>"><?php echo $key->nama;?></option>
                <?php foreach ($id_user as $row) { ?>
                <option value="<?php echo $row->id_user; ?>"> <?php echo $row->nama; ?></option>

                <?php } ?>
                </select>
           <span class="help-block"></span>
          </div>
        </div>
      </div>  
          </div>
          <!-- /.box-body -->
          <div class="box-footer">
           <button class="btn btn-danger" type="reset" value="reset">Reset</button>
           <button class="btn btn-info">Update</button><br>
           <a href="<?php echo base_url(); ?>SuratMasuk/">Kembali</a>
          </form>
           <?php  
                }
                ?>
          </div>
          <!-- box-footer -->
          </div>
          <!-- /.box -->
    </div>
    <!-- /.col -->
  </div>
  <!-- /.row -->

</section>
<!-- /.content -->

Current Result : result from codes above


Manage to solve the problem by my self.

i change my controller to this:

public function add_sm_proses(){
    $data = array(
        'no_surat'=>$this->input->post('no_surat'),
        'id_status'=>$this->input->post('id_status')    
    );
    $insert = $this->M_sm->trans_surat_user($data);
    if($insert=1){
        redirect('SuratMasuk');
    }   else {
        echo "<h2>Gagal menambahkan data</h2>";

    }
}

change my model to this :

public function trans_surat_user($data){
    $this->db->trans_start();
    $this->db->insert('surat', $data);
    $id_surat = $this->db->query('SELECT surat.id_surat FROM surat ORDER BY id_surat DESC limit 1');
    foreach ($id_surat->result() as $row) {
        $id_surat_result = $row->id_surat;
    }
    $id_user = $_POST['id_user'];
    foreach ($id_user as $data2) {
        array_push($id_user, $data2);
        $this->db->query('INSERT INTO surat_user (id_surat,id_user) VALUES ('.$id_surat_result.','.$data2.')');

    }
    $this->db->trans_complete();
}

Multiple Inserts, Update, Delete using Multiple Select in Codeigniter, Full Tutorial Multiple Insert, update and delete (CRUD) with multiple selected values in Codeigniter (Step-by-Step) The discussion this time is about how to make multiple Insert, Update, and delete using multiple selected values in Codeigniter. With a real case, a study example can make you understand well what kind of making multiple inserts, update, and delete and how it is applied.


class SuratMasuk extends CI_Controller {
    public function add_sm_proses(){
    $data = array(
                'no_surat'=>$this->input->post('no_surat'),
                'id_status'=>$this->input->post('id_status'),   
        );

Select MAX ID from table like this

    $id_surat = $this->db->query('SELECT MAX(surat.id_surat) AS maxid FROM surat')->row()->maxid;

Update:- $id_surat will give MAX ID present in the table. Don't use for next record. First, Increment it by value 1 and then use it

$id_surat = $id_surat + 1;
$id_user = $this->input->post('id_user') ? $this->input->post('id_user') : array();

First, check if $id_user have values or not otherwise foreach loop will give e error

    if(count($id_user) > 0){
        foreach ($id_user as $u){
            $data_values = array('id_surat' => $id_surat, 'id_user' => $u);
            $this->db->insert('surat_user', $data_values);
        }
    }
    $insert = $this->M_sm->add_sm($data);

$insert will not always return 1. So, only check if value exists

    if($insert){
            redirect('SuratMasuk');
        }   else {
            echo "<h2>Gagal menambahkan data</h2>";

        }
    }
}

Query Builder Class, This pattern allows information to be retrieved, inserted, and updated in your database When omitted, CodeIgniter assumes that you wish to select all fields and Multiple function calls can be made if you need several joins in one query. Insert, update and delete records with simple method chains of active record; Submits the user input in a secure way using parameters; Allows you to work with multiple database engines such as MySQL, SQL Server, etc. without rewriting the application code ; CodeIgniter uses drivers specific for each database engine in the background.


First, Show all record from DB and for each record add a button to edit the record.

Note:- Don't use <form> inside the loop

<a class="btn btn-warning btn-sm" href="<?= base_url('SuratMasuk/edit_sm/'.$row->id_surat)?>"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>Edit</a>

Controller for Edit

I'm just adding backend code here

where and table is reserved word for DB. It is better to not use it or use in another way.

public function edit_sm($id_surat){ 
    $condition_array = array('id_surat' => $id_surat);
    $data['surat'] = $this->M_sm->edit_sm($condition_array ,'surat');
}

Model for Edit

Get the record for edit

This function is getting only one record from DB so use row()

public function edit_sm($condition_array ,$record_in){     
    $this->db->join('status_surat', 'status_surat.id_status = surat.id_status');
    return $this->db->get_where($record_in, $condition_array )->row();
}

Now, Form for will show with data populated in it.

Getting updated data from Controller

public function edit_sm_proses() {
    $data = array(
        'id_surat'=> $this->input->post('id_surat'),
        'no_surat'=>$this->input->post('no_surat'),
        'id_status'=>$this->input->post('id_status'),
        'id_user'=>$this->input->post('id_user')
        );
    $condition_array = array(
    'id_surat' => $this->input->post('id_surat')
);

    $this->M_sm->edit_sm_proses($condition_array, $data, 'surat');
    redirect('SuratMasuk');
}

Updating data in Model

public function edit_sm_proses($condition_array, $data, $record_in){
    $this->db->where($condition_array);
    return $this->db->update($record_in, $data);
}

Query Builder Class, When omitted, CodeIgniter assumes that you wish to select all fields and Multiple function calls can be made if you need several joins in one query. instead of passing a data array directly to the insert or update functions:. Pembahasan kali ini adalah tentang bagaimana membuat multiple Insert, Update, dan delete dengan multiple selected value pada Codeigniter. Dengan contoh studi kasus yang nyata dapat membuat Anda memahami dengan baik seperti apa pembuatan multiple insert, update, dan delete dan bagaimana penerapannya.


Codeigniter Active Record: Insert, Select, Update, Delete, This pattern allows information to be retrieved, inserted, and updated in your results; Limiting or Counting Results; Query grouping; Inserting Data; Updating Data When omitted, CodeIgniter assumes that you wish to select all fields and Multiple function calls can be made if you need several joins in one query. Query Builder Class¶ CodeIgniter gives you access to a Query Builder class. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action. CodeIgniter does not require that each database table be its own


How to insert Multiple Checkbox value in CodeIgniter framework , When omitted, CodeIgniter assumes that you wish to select all fields and Multiple function calls can be made if you need several joins in one query. It can be used instead of passing a data array directly to the insert or update functions:. Here we using 3 files for insert Multiple Checkbox value in CodeIgniter framework MySQL PHP: Crud.php Path: codeIgniter\application\controllers\Crud.php; Crud_model.php Path: codeIgniter\application\models\Crud_model.php; multicheck_insert.php Path: codeIgniter\application\views\multicheck_insert.php


Update Multiple Selected Records with PHP, Codeigniter Active Record: Insert, Select, Update, Delete Allows you to work with multiple database engines such as MySQL, SQL Server, table names as array keys and assigns values to them; $this->db->insert('orders',  PHP CodeIgniter and JQuery AJAX append table row using jquery and insert all table data to database - Duration: 36:47. Software Tutorials 44,618 views