简体   繁体   中英

MySQL import data from a csv file via LOAD DATA INFILE does not work

I tried so hard to get this command work. Nothing is happening. Here is my issue:

I have a .csv file which I am uploading to my server where I want to run a script to import all of the data into a MySQL table. The csv looks like this:

id;herstellernr;hersteller;firmenname;url
123;ABC;Hersteller1;Firmenname1;http://www.test.com
234;DEF;Hersteller2;Firmenname2;http://www.test2.de
345;GHI;Hersteller3;Firmenname3;http://www.test3.net

... and so on.

After uploading the csv file, I first want to create a new table (temporary) where my data should be imported. Creating the table works without any problems; getting my Data imported from the csv file doesn't.

Here is my script (which comes after the upload script):

$temp = $pdo->prepare("

CREATE TABLE ".$name."
(
   id int(11),
   herstellernr varchar(3),
   hersteller varchar(150),
   firmenname varchar(255),
   url varchar(100),
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

LOAD DATA INFILE '_csv/".$filename."' INTO TABLE ".$name."
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(id, herstellernr, hersteller, firmenname, url)

");

$temp->execute(array());

CREATE TABLE works but after that there is nothing happening with my LOAD DATA INFILE

Plus: I don't really know if it should be '\\n' or '\\r\\n'. Anyway both cases didn't work.

I tried really hard and I am sure the syntax is just right. But I can't make it. Can you help? Thank you

You cannot use multiple queries with PDO. You'll need to break them up into separate queries. Since you're not using bound parameters, you can skip the prepare, as well:

$pdo->query("CREATE TABLE ".$name."
(
   id int(11),
   herstellernr varchar(3),
   hersteller varchar(150),
   firmenname varchar(255),
   url varchar(100),
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci");

$pdo->query("LOAD DATA INFILE '_csv/".$filename."' INTO TABLE ".$name."
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(id, herstellernr, hersteller, firmenname, url)");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM