hybmg57 Posted February 12, 2011 Share Posted February 12, 2011 Hi, Is there a way we can use PHP script to insert a CSV file into MySQL with CSV's first row as field names in MySQL? Quote Link to comment Share on other sites More sharing options...
mapleleaf Posted February 12, 2011 Share Posted February 12, 2011 If you know what the field names are and how many you just skip the first row. Like this: $row = 0; if (($handle = fopen($path_to_csv, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) { $num = count($data); //echo "<p> $num fields in line $row: <br /></p>\n"; if($row > 1) { $sql = "INSERT INTO your_table VALUES ('','".mysql_real_escape_string($data[0])."','".mysql_real_escape_string($data[1])."','".mysql_real_escape_string($data[2])."','".mysql_real_escape_string($data[3])."','".mysql_real_escape_string($data[4])."','','".mysql_real_escape_string($data[5])."','".mysql_real_escape_string($data[6])."','".mysql_real_escape_string($data[7])."','".mysql_real_escape_string($data[8])."','')"; mysql_query($sql) or die(mysql_error()); } $row++; } fclose($handle); } Something like that. This is code which did do that for a site but I haven't checked it. Obviously the number of fields is up to you. Quote Link to comment Share on other sites More sharing options...
fenway Posted February 13, 2011 Share Posted February 13, 2011 There's a CSV ENGINE type that makes all of this not an issue. Quote Link to comment Share on other sites More sharing options...
hybmg57 Posted February 13, 2011 Author Share Posted February 13, 2011 Hi fenway, What do you mean by CSV ENGINE type? Sorry I'm a beginner. Quote Link to comment Share on other sites More sharing options...
fenway Posted February 14, 2011 Share Posted February 14, 2011 See here. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.