Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Wie verwende ich for-each-Schleife beim Einfügen von Arrays in mysql mit Codeigniter?

Dies ist die Antwort, von der ich hoffe, dass sie vielen Menschen helfen wird :)

Dies ist meine Ansichtsseite:

    <div id="invoice_form">
    <?php echo form_open(base_url().'sample/myinvoice'); ?>
    <div><?php echo form_input(array('id'=>'ref','name'=>'ref'));?></div>
    <div  id="description"><p id="add_field">ADD DESCRIPTION</p></div>
    <input id="btn_add" name="btn_add" type="submit" class="btn btn-primary" value="Save" />
    <?php echo form_close(); ?>
    </div>
    <script>
    var count = 0;
    $(document).ready(function() {
    $('p#add_field').click(function(){
       count += 1;
       var html='<strong>Description  '+ count +'</strong>'+'<input id="description'+ count +'"name="description[]'+'" type="text" />'+'<input id="description'+ count +'"name="voucher_no[]'+'" type="text" />'+'<input id="description'+ count +'"name="price[]'+'" type="text" /><br />';
       $('#description').append(html); });
       });
    </script>

Dies ist mein Controller :

function myinvoice()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('ref', 'REFERENCE NO', 'trim');
        $this->form_validation->set_rules('description[]', 'DESCRIPTIONS', 'trim'); 
        $this->form_validation->set_rules('voucher_no[]', 'DESCRIPTIONS', 'trim'); 
        $this->form_validation->set_rules('price[]', 'DESCRIPTIONS', 'trim'); 

        if($this->form_validation->run())
        {
            $this->load->database();
            $this->load->model('sample_model');

            $ref =  $this->input->post('ref');
            $description = $this->input->post('description');
            $voucher_no = $this->input->post('voucher_no');
            $price = $this->input->post('price');
             $i = 0;
             if($description){
            foreach($description as $row)
            {
            $data['ref_no'] = $ref;
            $data['descriptions'] = $description[$i];
            $data['voucher'] = $voucher_no[$i];
            $data['value'] = $price[$i];
             $this->db->insert("description",$data);
            $i++;
            }}
            }else{
            print_r(validation_errors());
            }}