I have a lot of csv files in a directory. With these files, I have to write a script that put their content in the right fields and tables of my database. I am almost beginn
MySQL provides a wonderful feature that allows you to import a CSV file directly, in a single query.
The SQL command you're looking for is LOAD DATA INFILE
Manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Quick example:
LOAD DATA INFILE 'fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(
field1,
field2,
field3,
@variable1,
@variable2,
etc
)
set
(
field4 = concat(@variable1,@variable2)
);
That's a fairly basic example, but it covers most of what you'd want. The manual page gives full details of how to do some very complex stuff with it.
Hope that helps.
after
foreach ($row as $field) {
echo $field . '<br />';
You need to parse the result after ;
like:
$pieces = explode(";", $field);
and then insert every piece into the database
$sql = ' INSERT INTO X VALUES ("'.$pieces[0].'","'.$pieces[1].'","'.$pieces[2].'","'.$pieces[3].'","'.$pieces[4].'")';
mysql_query($sql, $conn);
Also mysqlimport can be used
private function runImport($host, $username, $password, $schema, $csvFilePath) {
$output = array();
$cmd = "/usr/bin/mysqlimport --host=$host";
$cmd .= ' --fields-terminated-by=\',\' --fields-optionally-enclosed-by=\'"\' ';
$cmd .= ' --user=' . $username . ' --password='. $password;
$cmd .= " $schema $csvFilePath";
exec($cmd, $output, $retVal);
foreach ($output as $line) {
echo "$line\n";
}
echo "\n\nReturn code : $retVal";
}