user1933865
user1933865

Reputation:

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");

Upvotes: 2

Views: 4626

Answers (3)

shail85
shail85

Reputation: 27

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);

Upvotes: 0

donlaur
donlaur

Reputation: 1287

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/

Upvotes: 0

Suku
Suku

Reputation: 3880

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

Upvotes: 4

Related Questions