Jump to content

PHP Script to Insert CSV into MySQL with first row as field names


hybmg57

Recommended Posts

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.

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.