我在将 csv 插入数据库时遇到问题。这是我的 csv 内容示例:
gender,age,name,location
male,21,jayvz,spl
female,21,jacyn,srl
这是表的表结构:
- id(自动递增)
- 联系方式
- 标签
- 值(value)
我需要做的是将数据从 csv 插入到该表中,如下所示:
预期输出:
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
(对预期的输出感到抱歉)
有什么想法吗?或者这甚至可能吗?
代码:
$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;
最佳答案
试试这个:
$row = 1;
$labels = array();
if (($handle = fopen("your.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row==1){
$labels = $data;
} else {
foreach ($data as $key=>$value) {
$query = "insert into table values (null,$row,'{$labels[$key]}','$value')";
$this->db->query($query)
}
}
$row++;
}
fclose($handle);
}
关于php - 将 CSV 内容保存到 mysql 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21877307/