codeigniter数组和循环插入多个数据

时间:2014-10-02 02:24:40

标签: php mysql codeigniter

我想发一张发票。出于这个原因,我需要一次插入多个数据。例如,我想一次输入db 5类别销售或购买产品。但我对 insert_batch 不感兴趣。我尝试但我在db中得到了一些空值。

我的模特是:

 <?php
 class Purchase_model extends CI_Model{

  public function purchase(){


  $price = $this->input->post('price');
  $quantity = $this->input->post('quantity');
  $date = $this->input->post('date');
     $vendor_name = $this->input->post('vendor_name');
     $model = $this->input->post('model');

    $invoice_no = $this->input->post('invoice');
    //$temp = count($this->input->post('vendor_name'));
  for($i=0; $i<10; $i++){  
    $data = array(
     'date'=>$date[$i], 
     'vendor_name'=>$vendor_name[$i],
     'model'=>$model[$i],
     'price' =>$price[$i], 
     'purchase_quantity'=>$quantity[$i],
     'amount'  =>$price[$i]*$quantity[$i],
     'invoice_no'=>$invoice_no[$i]
     );

      $insert = $this->db->insert('purchase',$data);
     return $insert; }
      }}

我的控制器是:

public function purchase(){

    if($this->Purchase_model->purchase()){

        $this->session->set_flashdata('Success', 
            'You are entered data successfully');
        redirect('home/purchase_form');
    }
}

我的观点例如:

  <?php echo form_label ('Price:'); ?>   
      <select name="price[]" id="price" class="input-xlarge">

      </select>



      <?php echo form_label ('Quantity'); ?> 

      <?php 
            $data = array ('name'      =>'quantity[]',
           'class'     =>'input-xlarge',
           'value'     => set_value('quantity')); ?>

      <?php echo form_input ($data); ?>

      <?php echo form_label ('Price:'); ?>   
           <select name="price[]" id="price2" class="input-xlarge">

           </select>

      <?php echo form_label ('Quantity'); ?> 

      <?php 
           $data = array ('name'      =>'quantity[]',
           'class'     =>'input-xlarge',
           'value'     => set_value('quantity')); ?>

      <?php echo form_input ($data); ?>

请帮忙。

1 个答案:

答案 0 :(得分:1)

问题已经解决了。我模特中的错误。正确的模型是

public function purchase(){

$data = array();
$temp = count($this->input->post('quantity'));

 for($i=0; $i<$temp; $i++){

$invoice_no  =   $this->input->post('invoice');
$date        =   $this->input->post('date');
$price       =   $this->input->post('price');
$quantity    =   $this->input->post('quantity');
$vendor_name =   $this->input->post('vendor_name');
$model       =   $this->input->post('model');
  if(  $quantity[$i]!= '') {    
$data[] = array(
     'date'=>$date, 
     'vendor_name'=>$vendor_name[$i],
     'model'=>$model[$i],
     'price' =>$price[$i], 
     'purchase_quantity'=>$quantity[$i],
     'amount'  =>$price[$i]*$quantity[$i],
     'invoice_no'=>$invoice_no
     );} }

      $insert = count($data);

            if($insert)
            {
            $this->db->insert_batch('purchase', $data);
            }

            return $insert;
      } 

感谢每一位试图帮助我的人。