0
Parts No    Mfg     Cond    LowPrice    AvgPrice    HighPrice  Weighted TotalQty
002805-00   3COM    NEW     25          25          25         N/A      1
0231A085    3COM    NEW     133.75      133.75      133.75     N/A      3
0231A61N    3COM    NEW     253.58      253.58      253.58     N/A      2
0231A61P    3COM    NEW     467.25      467.25      467.25     N/A      1

我只希望将此 csv 格式的 partno 、 mfg 和 price 添加到具有不同字段名称的表中,如第一行中定义的那样,但表中还包含一些其他字段。

这是正确的插入方式??????建议。

    if (($handle = fopen("sample.csv", "r")) !== FALSE) {
              while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {

                $i=0;
                if ($scount == 0) {  
                        foreach ($data as $key=>$value){
                         $item[$i++] = $value; 
                         if($value == 'Parts No') $c1 = $key;
                         if($value == 'Mfg') $c2 = $key;if($value == 'Cond') $c3 = $key;

                         if($value == 'AvgPrice') $c4 = $key;

                        }

                }else{
                if($data[$c3] == "NEW" || $data[$c3] == "new"){
                mysql_query("insert into  vable (partno,brand,price)
                    values('".$data[$c1]."','".$data[$c2]."','".$data[$c4]."') ",);}
                }

                $scount++; 

        } 
4

2 回答 2

0

使用此函数从 csv 文件中获取键值对,其中键位于 csv 文件的第一行

function get_data_csv_assoc($file){
    $full_data = array();
    if (($handle = fopen($file, "r")) !== FALSE) {
        if(($keys = fgetcsv($handle, 1000, ",")) !== FALSE) {

        }
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $array = array();
            foreach($keys as $key => $val){
                $array[$val] = $data[$key];
            }
            array_push($full_data,$array);
        }
        fclose($handle);
    }
    return $full_data;
}

经测试..

然后使用键值对进行数据插入。

$return_array = get_data_csv_assoc('filename');
foreach($return_array as $data){
mysql_query("insert into  vable (partno,brand,price)
                    values('".$data["Parts No"]."','".$data['Mfg']."','".$data['LowPrice']."') ",);}
                }
}
于 2012-04-16T12:27:02.800 回答
0

尝试

$sql = "INSERT INTO table (partno,brand,price) VALUES ('%s','%s','%s') ";
if (($handle = fopen ( "sample.csv", "r" )) !== FALSE) {
    $x = 0;
    while ( ($data = fgetcsv ( $handle, 10000, "," )) !== FALSE ) {

        if ($x == 0) {
            continue; // Remove headers
        }
        mysql_query ( sprintf ( $sql, mysql_real_escape_string ( $data [0] ), mysql_real_escape_string ( $data [4] ), mysql_real_escape_string ( $data [2] ) ) );
        $x ++;
    }

    fclose ( $handle );
}
于 2012-04-16T12:14:25.860 回答