0

我正在尝试上传.csv文件,然后将每一行保存到mysql数据库中。因此,对于文件中的每一行.csv,我想在我的mysql数据库中创建一行。请原谅我的英语,但我希望你明白我的意思。

到目前为止,我能够从第一行获取数据:

$path   = $targetPath;
$row    = 1;

if (($handle = fopen($path, "r")) !== FALSE) {

    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {

        $row++;
        $dataEntries[] = $data ;

    }

    fclose($handle);

} else{

    echo("There has been an error parsing ".$csvname);

}

//Everything seems to be okay, we can save it
foreach($dataEntries as $line){

    $oName  = $line[0];
    $oUrl   = $line[1];
    $oType  = $line[2];
    $oDescr = $line[3];

    //If there is just one row in the csv file, Output: "string"
    //If there are more rows, than the output is "stringstring1string2"
    echo($oName);

}

更新

只是为了让每个人都知道:@Greg P 的解决方案效果很好,但我必须将 LOCAL 添加到 infile 命令,以便我可以访问上传到我的服务器的 csv 文件:

LOAD DATA LOCAL INFILE '$targetPath' INTO TABLE tableName FIELDS TERMINATED BY ';' (name,url,type,descr)
4

1 回答 1

8

为什么不使用 LOAD DATA INFILE,如下所示:

LOAD DATA INFILE 'filename.csv' 
INTO TABLE filenames
FIELDS TERMINATED BY ',' 
(Name, Url, Type, Descr)
于 2012-05-13T14:48:53.113 回答