PHP +将多个行从.csv保存到mysql [英] PHP + Save multiple rows from .csv to mysql
问题描述
我试图上传一个 .csv
文件,然后将每行保存到 mysql
db。因此对于 .csv
文件中的每一行,我想在我的 mysql
db中创建一行。请原谅我的英语,但我希望你能得到我的意思。
我已经到目前为止,我能够从第一行获取数据:
$ path = $ targetPath;
$ row = 1;
if(($ handle = fopen($ path,r))!== FALSE){
while(($ data = fgetcsv ,;))!== FALSE){
$ row ++;
$ dataEntries [] = $ data;
}
fclose($ handle);
} else {
echo(解析过程中出现错误。$ csvname);
}
//一切似乎都没关系,我们可以保存它
foreach($ dataEntries as $ line){
$ oName = $ line [0];
$ oUrl = $ line [1];
$ oType = $ line [2];
$ oDescr = $ line [3];
//如果csv文件中只有一行,则输出:string
//如果有更多行,则输出为stringstring1string2
echo ($ oName);
}
UPDATE
只是为了让every1知道:@Greg P的解决方案很好,但我必须添加LOCAL到infile命令,以便我可以访问上传到我的csv文件服务器:
LOAD DATA LOCAL INFILE'$ targetPath'INTO TABLE tableName FIELDS TERMINATED BY';'(name,url,type, descr)
为什么不使用LOAD DATA INFILE,这个:
LOAD DATA INFILE'filename.csv'
INTO TABLE filenames
FIELDS TERMINATED BY' '
(Name,Url,Type,Descr)
I am trying to upload a .csv
file and than save each row to a mysql
db. So for each row in the .csv
file, I would like to create a row in my mysql
db. Excuse my english, but I hope you get what I mean.
I have got so far, that i am able to get the data from the first row:
$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);
}
UPDATE
Just to let every1 know: @Greg P ´s solution worked great, but I had to add LOCAL to the infile command, so that I could access the csv file that was uploaded to my server:
LOAD DATA LOCAL INFILE '$targetPath' INTO TABLE tableName FIELDS TERMINATED BY ';' (name,url,type,descr)
Why not use LOAD DATA INFILE, something like this:
LOAD DATA INFILE 'filename.csv'
INTO TABLE filenames
FIELDS TERMINATED BY ','
(Name, Url, Type, Descr)
这篇关于PHP +将多个行从.csv保存到mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!