如何在codeigniter中循环插入数据到数据库?

我希望使用循环插入数据到我的数据库.我有看法,名字是’form.php’.

<!-- STEP 3 -->
<fieldset>
    <h2>Kebutuhan Khusus</h2><p>(bila ada)</p>
<div class="form-group">
<label>Calon Mahasiswa</label>
  <select name="keb[0][jns_kebutuhan]" class="form-control" id="cama">
    <option value="">--Jenis Kebutuhan--</option>
    <option value="Tuna Netra">Tuna Netra</option>
    <option value="Tuna Grahita">Tuna Grahita</option>
    <option value="Tuna Wicara">Tuna Wicara</option>
    <option value="Tuna Rungu">Tuna Rungu</option>
    <option value="Tuna Daksa">Tuna Daksa</option>
    <option value="Lainnya">Lainnya</option>
  </select>
  <input type="hidden" class="form-control" name="keb[0][subjek]" value="Calon Mahasiswa">
</div>
<div class="form-group">
<label>Ayah</label>
  <select name="keb[1][jns_kebutuhan]" class="form-control" id="ayah">
    <option value="">--Jenis Kebutuhan--</option>
    <option value="Tuna Netra">Tuna Netra</option>
    <option value="Tuna Grahita">Tuna Grahita</option>
    <option value="Tuna Wicara">Tuna Wicara</option>
    <option value="Tuna Rungu">Tuna Rungu</option>
    <option value="Tuna Daksa">Tuna Daksa</option>
    <option value="Lainnya">Lainnya</option>
  </select>
  <input type="hidden" class="form-control" name="keb[1][subjek]" value="Ayah">
</div>
<div class="form-group">
<label>Ibu</label>
  <select name="keb[2][jns_kebutuhan]" class="form-control" id="ibu">
    <option value="">--Jenis Kebutuhan--</option>
    <option value="Tuna Netra">Tuna Netra</option>
    <option value="Tuna Grahita">Tuna Grahita</option>
    <option value="Tuna Wicara">Tuna Wicara</option>
    <option value="Tuna Rungu">Tuna Rungu</option>
    <option value="Tuna Daksa">Tuna Daksa</option>
    <option value="Lainnya">Lainnya</option>
  </select>
  <input type="hidden" class="form-control" name="keb[2][subjek]" value="Ibu">
</div>

我的控制器’Pascasarjana.php’

foreach ($_POST['keb'] as $keb) {
    $this->m_pascasarjana->kebutuhan('tbl_kebutuhan',$keb);
  }

而我的模型是

function kebutuhan($table,$data) {
  $last_row = $this->db->select('id_pendaftar')->order_by('id_pendaftar',"desc")->limit(1)->get('tbl_datapribadi')->row()->id_pendaftar;
  $data['id_pendaftar'] = $last_row;
  $query = $this->db->insert($table,$data);
  return $this->db->insert_id();
} //END FUNCTION//

我尝试使用我的控制器,如果其中一个表单未填充数据在我的数据库中包含0.我想如果我没有填写其中一个表单,数据库中没有填充数据.怎么做?

最佳答案 试试这个

function kebutuhan($table,$data) 
{
  $last_row = $this->db->select('id_pendaftar')->order_by('id_pendaftar',"desc")->limit(1)->get('tbl_datapribadi')->row()->id_pendaftar;
  if(!empty($data['jns_kebutuhan']))
  {
     $data['id_pendaftar'] = $last_row;
     $query = $this->db->insert($table,$data);
  }
  return $this->db->insert_id();
} //END FUNCTION//
点赞