从csv插入数据

时间:2012-04-16 12:11:19

标签: php mysql

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添加到具有不同字段名称的表中,如第1行中所定义,但表中还包含其他一些字段。

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

    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++; 

        } 

2 个答案:

答案 0 :(得分: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 );
}

答案 1 :(得分: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']."') ",);}
                }
}