sunshine
sunshine

Reputation: 67

How to insert a dynamic form values into database in php

how to insert form values(dynamic checkbox,input) dynamically into database This my view file:

<form action="<?php base_url('controller/insert'); ?>"> 
    <table>
        <thead>
            <tr> 
                <th>Menu Id</th> 
                <th>Menu Name</th> 
                <th>Yes/No</th> 
            </tr> 
        </thead>
        <tbody>
            <?php foreach($result as $res) { ?>
                <tr> 
                    <td><input type="text" name="menu_id[]" value="<?= $res->menu_id ?>"></td> 
                    <td><input type="text" name="menu_name[]" value="<?= $res->menu_name ?>"></td> 
                    <td><input type="checkbox" name="yes[]" value="<?= $res->menu_id ?>"></td> 
                </tr> 
            <?php } ?>
        </tbody>
    </table>
</form>

this my controller function:

<?php
    $fields = array(
        'menu_id'   => $this->input->post('menu_id'),
        'menu_name' =>  $this->input->post('menu_name'),
        'yes'       =>$this->input->post('yes')
    );
    $this->db->insert('menu_table',$fields);
?>

when i print this array $fields it displays as:

Array ( [0] => 2 [1] => 3 ) Array ( [0] => Plant [1] => Line ) Array ( [0] => on [1] => on ).

this my form:the menuid and menu desc and checkbox displaying dynamically.i need to insert into table as same as the form below displays. enter image description here

Upvotes: 0

Views: 851

Answers (1)

Alex
Alex

Reputation: 9265

You need to loop through the arrays. You can use the menu id as the key as it is sequential e.g. the first of menu_id corresponds with the first of menu_name:

$menu_id = $this->input->post('menu_id');
$menu_name = $this->input->post('menu_name');
$yes = $this->input->post('yes');

$yes = is_null($yes) ? array() : array_flip($yes);

if (is_null($menu_id) || is_null($menu_name)) {
    show_error('Parameters missing');
}

// should really be in a model
foreach ($menu_id as $key => $value) {
    $data['menu_id'] = $value;
    $data['menu_name'] = $menu_name[$key];
    $data['yes'] = isset($yes[$value]) ? 'true' : 'false';
    $this->db->insert('menu_table',$data);
}

Upvotes: 3

Related Questions