2016-08-05 17 views
1

我的控制器看起來如何編寫條件來檢查不在codeigniter中的數據庫表中的csv文件數據?

public function importcsv() 
{ 

    $data['menu'] = $this->AdminModel->get_menu(); 
    $data['error'] = ''; //initialize image upload error array to empty 

    $config['upload_path'] = './assets/uploads/'; 
    $config['allowed_types'] = 'csv'; 
    $config['max_size'] = '1000'; 

    $this->load->library('upload', $config); 


    // If upload failed, display error 
    if (!$this->upload->do_upload()) 
    { 
     $data['error'] = $this->upload->display_errors(); 

     $this->load->view('csvindex', $data); 
    } 
    else 
    { 
     $file_data = $this->upload->data(); 
     $file_path = './assets/uploads/'.$file_data['file_name']; 

     if ($this->csvimport->get_array($file_path)) 
     { 

      $csv_array = $this->csvimport->get_array($file_path); 
      foreach ($csv_array as $row) 
      { 


       $data1['mid']=$row['mid']; 
       $data1['category']=$row['category']; 
       $data1['name']=$row['name']; 
       $data1['price']=$row['price']; 
       $data1['description']=$row['description']; 


        if($this->db->where('mid', $data1['mid'])) 
        { 

         $this->db->update('menu', $data1); 
        } 
         if($this->db->where("mid <>",$data1['mid'])) 
         { 


          $this->db->insert('menu', $data1); 
         } 



      }   

      $this->session->set_flashdata('success', 'Csv Data Imported Succesfully'); 
      redirect(base_url().'Admin/menu'); 

     } 
     else 
     { 
      $data['error'] = "Error occured"; 
      $this->load->view('csvindex', $data); 
     } 

    } 
} 

使用條件

if($this->db->where('mid', $data1['mid'])) 
    { 

     $this->db->update('menu', $data1); 
    } 

我可以更新菜單表中的內容,其中中旬等於csv文件中旬($ data1 ['mid'])。它的工作很好。

我需要的是我要插入記錄時中旬菜單表csv文件沒有。對於我使用的條件

if($this->db->where("mid <>",$data1['mid'])) 
    { 
     $this->db->insert('menu', $data1); 
    } 

,但它不工作,它的工作當如果中期csv文件沒有在菜單表,然後將其插入整個csv文件內容到表。

我的需求是我只需要插入不在菜單表中的記錄。如何編寫該條件。我很長一段時間都在努力,我對這種情況很陌生。提前感謝。所有的

回答

0

首先我要表明的東西,

您正在做大量的數據庫操作的foreach循環,這是不好的性能因素。你應該先準備查詢,然後立即開火。

而其他的事情是,你正在檢查數據庫中的記錄通過PHP代碼和解僱查詢。而不是你應該只在MySQL中進行檢查。

下面是您可以根據自己的參數實施的解決方案的大致思路。

如果不存在,則可以編寫一個檢查表中現有記錄的查詢,然後將其插入表中。

WHERE NOT EXISTS 

這可以用於您的查詢。

還有一個你可以附加更多的查詢,並使用codeigniter的insert_batch函數立即啓動它。

粗糙的結構會像

foreach(x as y) { 
    //push all data to array $queries; 
} 
$this->db->insert_batch('menu',$queries); 
相關問題