note 89895 deleted from function.fgetcsv by danbrown
| From: | danbrown@php.net | Date: | Fri, 27 Mar 2009 15:42:03 +0000 |
| Subject: | note 89895 deleted from function.fgetcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-152531@lists.php.net to get a copy of this message | ||
Note Submitter: jnolten at gmail dot com
Reason: bad code
----
Script to insert the contents of a .csv file ($file in this case) into a MySQL database using more
than one delimiter (so for instance you could use both ; and ,).
Useful because Excel outputs CSV-files with semicolons instead of comma's.
The CSV file must look like this:
[tablename]
[column1],[column2],[column3] etc
[value1row1],[value2row1],[value3row1] etc
[value1row2],[value2row2],[value3row1]
etc
So the value matches with the column.
$data = nl2br(file_get_contents($file));
$data = split("<br />", $data);
$num = count($data);
for ($i = 0; $i <= $num; $i++) {
$data[$i] = split("[,;]", $data[$i]);
$data[$i][0] = str_replace(" ", "", $data[$i][0]);
if ($i == 0) $table = $data[$i][0];
elseif ($i == 1) $column = join(', ', $data[$i]);
else {
$data[$i][0] = ltrim(rtrim($data[$i][0]));
$values = join("', '", $data[$i]);
mysql_query("INSERT INTO ".$table." (".$column.") VALUES
('".$values."')");
if (mysql_error() == '') echo $data[$i][1].' has been added to the database';
//In my CSV files the second column always contains a name
else echo mysql_error();
echo '<br>';
}
}