Jump to content

Multiple CSV Import


jbalanski

Recommended Posts

Hi could someone help with this? I need to import multiple CSV files into a mysql database then move the csv files to a log directory. I can import one csv with the following but how to I import multiple files ....each file only has one row of data. Also how would I move the csv file after import to another directory. Also if I put a record ID field in the table the import won't work any suggestions on that would be helpful.

Thanks

<?php
$connection = mysql_connect("localhost", "user", "password") or die ("Unable to connect to server");
$db = mysql_select_db("DATABASE", $connection) or die ("Unable to select database");
$fcontents = file ('test.csv');
for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i], ',' );
echo "$line<BR>";
$arr = explode(",", $line);
echo "$arr";
$sql = "insert into TABLE values ('". implode("','", $arr)."')";
mysql_query($sql);
echo $sql ."<br>\n";
if(mysql_error()) {
echo mysql_error() ."<br>\n";
}
}
?>
Link to comment
https://forums.phpfreaks.com/topic/34642-multiple-csv-import/
Share on other sites

[quote author=jbalanski link=topic=122882.msg507333#msg507333 date=1169072306]
how to I import multiple files ...[/quote]
[code]
<?php
$connection = mysql_connect("localhost", "user", "password") or die ("Unable to connect to server");
$db = mysql_select_db("DATABASE", $connection) or die ("Unable to select database");

function cvstosql($file) {
$fcontents = file ($file);
for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i], ',' );
echo "$line<BR>";
$arr = explode(",", $line);
echo "$arr";
$sql = "insert into TABLE values ('". implode("','", $arr)."')";
mysql_query($sql);
echo $sql ."<br>\n";
if(mysql_error()) {
echo mysql_error() ."<br>\n";
}
}
}
cvstosql('file1.cvs');
cvstosql('file2.cvs');
cvstosql('file3.cvs');[/code]
That's just using your code, and assuming it works correctly. I only made minor changes.


[quote]Also how would I move the csv file after import to another directory.[/quote]
rename() or copy().
http://us2.php.net/manual/en/function.rename.php
http://us2.php.net/manual/en/function.copy.php


[quote]Also if I put a record ID field in the table the import won't work any suggestions on that would be helpful.[/quote]Without seeing your database structure and cvs file, I can't comment on that.
Link to comment
https://forums.phpfreaks.com/topic/34642-multiple-csv-import/#findComment-163301
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.