PDA

View Full Version : Problem with LOAD DATA INFILE


fail
12-08-2009, 07:11 AM
I have a problem with a file import to MySQL. Not sure if this belongs to MySQL or PHP. Via phpmyadmin it works fine with this string:

LOAD DATA INFILE 'C:\\xampp\\tmp\\import.csv'
INTO TABLE `parts`
FIELDS TERMINATED BY ','
ENCLOSED BY '"' ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'

Works perfectly. phpmyadmin generates me this php code:

include("connect.php");

$sql = "LOAD DATA LOCAL INFILE \'C:\\\\xampp\\\\tmp\\\\parts_import.csv\'
INTO TABLE `parts`
FIELDS TERMINATED BY \',\'
ENCLOSED BY \'\"\'
ESCAPED BY \'\\\\\'
LINES TERMINATED BY \'\\r\\n\'# 481 row(s) affected.\n"
. "";

$result = mysql_query($sql);
echo mysql_error();
echo $result;

That results in into this error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'C:\\xampp\\tmp\\import.csv\' INTO TABLE `parts` FIELDS TERMINATE' at line 1

I presume the error is with one, or several of the '/', but after trying about 1000 different strings I give up now. I hope anybody has a hot hint for me.

BubikolRamios
12-08-2009, 04:32 PM
have no idea, but mybe:
\`parts\`

Fumigator
12-08-2009, 04:58 PM
You do not escape single quotes when encapsulating a string with double quotes.

String rules (http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.double)

fail
12-17-2009, 04:41 AM
I found a cool workaround without LOAD INFILE. PHP has a fgetscsv function and I found inspiration and samples here: http://hk2.php.net/fgetcsv . Specially rt10k's sample looked close to what I wanted.

Now I place the CSV file in the php file directory and when I use this code:

<?php
include("/css/connect.php");

$row = 0;
$handle = fopen("parts.csv", "r");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// the first line in the CSV file is ignored
$num = count($data);

$row++;
for ($c=0; $c < $num; $c++) {

}

} else {

$num = count($data);

$row++;
for ($c=0; $c < $num; $c++) {

}

$query =
"INSERT INTO partspool
(id, project, quantity, custpartno, description, footprint, partno, designation, currency, cost, note1, notebom)
VALUES ('','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."','".$data[5]."',
'".$data[6]."','".$data[7]."','".$data[8]."','".$data[9]."','".$data[10]."',
'".$data[11]."')" or die(mysql_error());

}
}
fclose($handle);
?>


This code ignores the first line, which are usually row headers. Works perfectly for me!