Using PHP to import CSV data into mySQL, Part 2
Following up on my last thread. Trying to import a user-generated CSV into MySQL via a PHP upload script. Uploads successfully, but I am not able to use LOAD DATA due to a permissions problem. Here is what I am trying to do instead:
$row = 1;
if (($handle = fopen($target_path, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
echo "<p> $num field开发者_JS百科s in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++)
{
$fullRow = $fullRow . $data[$c] . "," ;
}
echo $fullRow;
mysql_query("INSERT INTO foo (field1, field2, field3, field4) VALUES ('$fullRow')");
$fullRow = NULL;
}
fclose($handle);
}
echo $fullRow
spits out a verbatim copy of the line from the CSV file, except for an additional comma on the end. Is this why the Insert is not working correctly? When I do a manual upload via phpMyAdmin, the CSV file is imported without issue. Or is there a problem with the VALUE ('$fullRow')
bit of the code?
You can simply remove the last comma.
for ($c=0; $c < $num; $c++)
{
$fullRow = $fullRow . $data[$c] . "," ;
}
echo $fullRow;
$fullRow = substr($fullRow,0,-1);
And also you script is not ok.
mysql_query(" INSERT INTO foo (field1, field2, field3, field4) VALUES ('$fullRow') " );
$fullRow = NULL;
Paolo_NL_FR's fixes should get you up and running. The script could use some TLC though, and does not have even basic sql injection protection. Try something like this perhaps:
if (($handle = fopen($target_path, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$values = implode(",", array_map('mysql_real_escape_string', $data));
mysql_query("INSERT INTO foo (field1, field2, field3, field4) VALUES ($values);");
}
fclose($handle);
}
精彩评论