简体   繁体   中英

Importing .csv file into mysql in php

I have a .csv file with me but i am unable to import it into the database. I have parsed my .csv file using the below query. Can you please help me how to insert data into MySql.

My code is:-

$fp = fopen('test.csv','r') or die("can't open file");
print "<table>\n";

while($csv_line = fgetcsv($fp,1024)) 
{
    print '<tr>';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {

        print '<td>'.$csv_line[$i].'</td>';
        $data[] = $csv_line[$i];
    }
    print "</tr>\n";
}
print '</table>\n';
fclose($fp) or die("can't close file");

In MySQL we can import data from CSV file to a table very easily:

LOAD DATA LOCAL INFILE 'import.csv' INTO TABLE from_csv FIELDS TERMINATED BY ','  LINES TERMINATED BY '\n'  (FIELD1, FIELD2, FIELD3);

http://dev.mysql.com/doc/refman/5.0/en/load-data.html

Example: http://www.techtrunch.com/linux/import-csv-file-mysql-table

The code seems to take the csv file and export it out to the browser as a tabular data table.

You mentioned importing into a mysql table, but there are no mysql information listed. Create a mysql table and try to map your fields you are importing to database fields in a table. The easiest way for me is to use phpmyadmin to generate the load data sql although the load data local infile mentioned in an answer will work as well if you understand enough to change it.

When I learned how to do it I used this tutorial. http://vegdave.wordpress.com/2007/05/19/import-a-csv-file-to-mysql-via-phpmyadmin/

you can use this code. I hope this will be helpfull
//after uploading csv file from a upload file field
$handle = fopen($_FILES['csvfile']['tmp_name'], "r");

$header = fgetcsv($handle);

while(! feof($handle)){

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

$import="INSERT into csvtest($header[0], $header[1], $header[2], $header[3], $header[4], $header[5],$header[6]) values ('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]', '$data[5]', '$data[6]')";

mysql_query($import) or die(mysql_error());

}

}

fclose($handle);

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