2015-09-06 30 views
2

我有csv文件,我解析數組並傳遞給mysql表。 一些CSV文件不包含一些列什麼是在數據庫中,當我將它轉換爲數組比我有更少數量的列在表中,我得到「語法錯誤」。如果密鑰不存在,則發送null

從控制器I撥打:

function sendHistoric(){ 
     $this->load->model('Historic_model'); 
     $this->load->library('csvreader'); 
     foreach($this->divisions as $div){ 
      $result = $this->csvreader->parse_file("assets/csv/1516{$div}.csv");//path to csv file 
      $this->Historic_model->loadCSVtoDB($result); 
      //var_dump($result); 
     } 
    } 

模型我有:

function loadCSVtoDB($data){ 
    $sql = "call ins_historic(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; 

    foreach($data as $row){ 
     var_dump($row); 
     $this->db->query($sql,$row);  
    } 
    //echo $this->db->conn_id->error_message(); 
} 

我可以以某種方式發送NULL,而不是在那裏,他發現我的數據的數量較少或者我需要檢查數組中的每個元素是否存在,如果不是,則將其設置爲null?

回答

1

要考慮的一個選擇不是編寫較慢的PHP循環,而是利用LOAD DATA INFILE塊內的靈活代碼可能性,例如在此答覆鏈接here中看到的處理。功能,轉換可能是無止境的。

也許6個一半打另一個。但對於簡單的例程來說也不錯,我會建議一個快速的數據攝取。

編輯:(基於以下OP評論)

create table t62 
( c1 int not null, 
    c2 varchar(10) not null, 
    c3 int not null, 
    c4 char(5) not null, 
    someOther int not null, 
    -- an addtion 57 columns here 
    primary key(c1,c2,c3,c4) 
); 

-- Mimic the LOAD DATA INFILE or PHP loop: 
insert t62(c1,c2,c3,c4,someOther) values (1,'t',1,'01742',777); 
insert t62(c1,c2,c3,c4,someOther) values (1,'t',1,'01742',777); -- error 1062: Dupe PK 
insert t62(c1,c2,c3,c4,someOther) values (1,'t',2,'01742',777); -- happy 

所以我不知道,你會如何建議的代碼將挑選複合PK的嗎?如果是這樣,那麼這些數據如何與其他數據的關係發揮作用呢?

+0

我會嘗試像你描述的那樣,有62列,所以我需要設置每個列爲null,如果它爲空... – DocNet

+0

yikes,多麼痛苦! – Drew

+0

前4列是主鍵,我可以設置一些默認的數字或字符串intead null爲前4列使用此負載? – DocNet