我遇到了將csv插入數據庫的問題。這裏是我的CSV內容示例:將CSV內容保存到mysql數據庫中
gender,age,name,location
male,21,jayvz,spl
female,21,jacyn,srl
和這裏的表的表結構:
- ID(自動遞增)
- CONTACT_ID
- 標籤
- 值
我需要做的是將數據從csv插入到ta中竹葉提取這樣的:
預期輸出:
id | contact_id | label | value
1 | 1 | gender | male
2 | 1 | age | 21
3 | 1 | name | jayvz
4 | 1 | location | spl
5 | 2 | gender | female
6 | 2 | age | 21
7 | 2 | name | jacyn
8 | 2 | location | srl
(遺憾的預期輸出)
什麼想法?或者這甚至有可能?
CODE:
$headers = exec("head -n 1 {$paramfile}");
$param_names = array_filter(explode(",", $headers));
$param_count = count($param_names);
$contact_count = count($contacts);
$contactsfile = getcwd()."/uploads/".date('ymdhis').".cntctid";
$row = '';
$str_csv = array();
$tmp_handler = fopen($datafile, 'r');
$param_value = '';
while(($upload_str = fgets($tmp_handler, 4096)) !== FALSE){
$param_value = explode(",", $upload_str);
array_shift($param_value); // msisdn bb
$str_line = implode(",", $param_value);
//$age = array_shift($param_value);
//$row.= implode(",", $param_value);
//for($x = 0; $x < count($param_value); ++$x){
// $row.= $param_value[$x].",";
//}
$str_csv[] = str_getcsv($str_line, ",");
}
for($a = 0; $a < $param_count; ++$a){
for($i = 0; $i < $contact_count; ++$i){
$row = $contacts[$i].",".$param_names[$a].",'<the values should be here>'";
exec("echo '".$row."' >> ".$contactsfile);
}
}
$load_query = "LOAD DATA LOCAL INFILE '{$contactsfile}' INTO TABLE {$this->contact_details} ";
$load_query .= "FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' ";
$load_query .= "(contact_id, label_name, label_value)";
$this->db->query($load_query);
return $this->db->affected_rows() > 0;
顯示您的代碼.... –
[我怎樣才能將數據從CSV導入到MySQL?](http://stackoverflow.com/questions/9555370/how-i-can-import-data -from-csv-to-mysql) – randak
可能幾乎就是一切。請發佈您的代碼到目前爲止。 –