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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.