简体   繁体   中英

How to add Array to database in codeigniter?

I have a form with a multiselect field. I choose 3 categories for each company, but only one is added to the database.

How can I add an Array of 3 categories to my database? I use a joined table to add multiple categories to a company.

My table structure:

companies
---------
companyid
companyname
etc etc

categories
---------
categoryid
categoryname

companycategories
----------------
companycategoryid
categoryid
companyid

My controller:

function update()
{
    $id = $this->uri->segment(3);
    $data = array(
       'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
       'Postcode' => $this->input->post('Postcode'),
       'Plaats' => $this->input->post('Plaats'),
       'Telefoonnummer' => $this->input->post('Telefoonnummer'),
       'Email' => $this->input->post('Email'),
       'Website' => $this->input->post('Website'),
       'Profiel' => $this->input->post('Profiel'),
       'Adres' => $this->input->post('Adres'),
    );
    if($this->input->post('logo')) { $data['logo'] = $this->input->post('logo'); }
    $this->members_model->updatebedrijf($id, $data);

    $b = $this->session->userdata('idbedrijven');
    redirect("members/$b");
}   

My model:

function updatebedrijf($id, $data)
{

        $this->db->where('idbedrijven', $id);
        $this->db->update('bedrijven', $data); 

        $to_bedrijfcategorieen2['idcategorieen'] = $this->input->post('categorieen');
        $this->insert_bedrijfcat1($to_bedrijfcategorieen2); 

}

function insert_bedrijfcat1($data1) 
{ 
    echo '<pre>';
    print_r($data1);
    echo '</pre>';

    $id = $this->uri->segment(3); 
    $this->db->where('idbedrijven', $id);
    $this->db->update('bedrijfcategorieen', $data1); 

    return $this->db->affected_rows() >= 1 ? TRUE : FALSE; 
}

My form:

<tr>
<td><?= form_label('Categorieen'); ?></td>
<td><?= form_multiselect('categorieen[]', $opties, key($selectie)); ?></td>
</tr>

The output of print_r($data1); gives me this:

Array
(
    [idcategorieen] => Array
        (
            [0] => 11
            [1] => 12
            [2] => 13
        )

)

Hope it is clear.

To Update one to many relation here is the technique

 function insert_bedrijfcat1($data1) 
{     

$delete = $this->db->query("DELETE FROM `bedrijfcategorieen` WHERE `idbedrijven` = '" . $id. "'");

$id = $this->uri->segment(3); 

foreach($data1['idcategorieen'] as $cat_id){

$this->db->query("INSERT INTO `bedrijfcategorieen` (`idbedrijven`,`idcategorieen` ) VALUES ('".$id."','".$cat_id."')");

 }
 }

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