Jump to content

Help parsing csv file


mbk

Recommended Posts

Hi,

 

I am trying to parse a csv file and insert the contents into a mysql table.  I could use the insert local file option, but I dont want all the columns importing.  I have the following code, but this doesnt seem to work.

 

<?php

$table = 'suppliers';

$username = "user";
$pass = 'pass';
$db = mysql_connect("localhost", $username, $pass);
mysql_select_db("testdb",$db); 

$empty_table = "TRUNCATE TABLE $table";
mysql_query($empty_table) or die (mysql_error());

$file_handle = fopen("file.csv", "r");

while (!feof($file_handle) ) {

$tmp = fgetcsv($file_handle, 8192);

$category = ($tmp[0]);
$supp_pn = ($tmp[1]);
$desc = ($tmp[3]);
$help = ($tmp[5]);

$sql = "INSERT INTO $table SET category='$category', supp_pn='$supp_pn', desc='$desc', $help='help'";
mysql_query($sql)or die (mysql_error());

}

fclose($file_handle);

?>

 

An example of the data in the csv is below -

"","FUNDHD      ","","FUNDHD      ","",0.00,0.00,0

"[Pending Assignment]","ATS0057     ","                                        ","AT-FS705LE-30       ","Hama UK Ltd                   ",17.31,29.80,0

"[Pending Assignment]","MARKETING   ","                                        ","MARKETING   ","Hama UK Ltd                   ",20000.00,30000.00,0

 

Can someone help pls?

Link to comment
https://forums.phpfreaks.com/topic/194223-help-parsing-csv-file/
Share on other sites

Thanks for the quick reply - I made the amend and now get the following 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 'desc)VALUES('', 'FUNDHD      ', 'FUNDHD      ')' at line 1

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.