Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import large csv file to mysql database using php

I have a very large CSV file (150 MB). What is the best way to import it to MySQL? I have to do some manipulation in PHP before inserting it into the MySQL table.

like image 567
amazed Avatar asked Sep 23 '10 07:09

amazed


People also ask

What is the better way to read the large CSV file in PHP?

To read the file, we will use the fopen function of PHP, this inbuilt function is used to simply open a file from a local URL, it's used to bind a resource to a steam. It expects as second argument the mode in which we'll operate, in this case, just reading with the r identifier.


Video Answer


2 Answers

You could take a look at LOAD DATA INFILE in MySQL.

You might be able to do the manipulations once the data is loaded into MySQL, rather than first reading it into PHP. First store the raw data in a temporary table using LOAD DATA INFILE, then transform the data to the target table using a statement like the following:

INSERT INTO targettable (x, y, z)
SELECT foo(x), bar(y), z
FROM temptable
like image 117
Mark Byers Avatar answered Sep 24 '22 16:09

Mark Byers


I would just open it with fopen and use fgetcsv to read each line into an array. pseudo-php follows:

mysql_connect( //connect to db);

$filehandle = fopen("/path/to/file.csv", "r");
while (($data = fgetcsv($filehandle, 1000, ",")) !== FALSE) {
    // $data is an array
    // do your parsing here and insert into table
}

fclose($filehandle)
like image 32
thomasmalt Avatar answered Sep 22 '22 16:09

thomasmalt