Updating existing AND importing data into MySql using CSV

Discussion in 'PHP' started by jgarite, Jan 4, 2010.

  1. #1
    I have a csv file with 4 columns and headers. i tried to understand how to use fgestcsv, explode, and array, but i just couldnt grab the concepts in the time i have alloted for this project. it needs to be finished today and what i have is giving me errors.

    <?php
    $f = fopen("test2.csv","r");
    /*
    grab the file somehow, you can do a temp upload script fairly
    easily if need be, just ask and i can show you an example
    */
    
    $col_names = array("SKU","Options","Option_Value","Subvalue"); //etc
    /*
    if the csv's first row consists of col names, you can pull
    it from the first fgetcsv() - it'd be more modular than the above
    */
    
    $data = array();
    while(($line = fgetcsv($f,8192)) !== false)
        {
        for ($col=0;$col<count($line);$col++) $data[$col][] = $line[$col];
        }
    fclose($f);
    /*
    it's an extra step to push it all into an array (e.g. data[]) but
    i did in this example in case you want to validate it somehow
    */
    
    //connect to database
    $con = mysql_connect("xxx","xxx","xxx");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("xxx", $con);
    
    $tbl_name = "test";
    $fields = implode(",",$col_names);
    $num_rows = count($data);
    for ($i=0;$i<$num_rows;$i++)
        {
        $values = implode(",",$data[$i]);
        $q = "INSERT INTO ".$tbl_name." (".$fields.") VALUES (".$values.")";
        mysql_query($q) or exit("error: ".mysql_error() . $q);
        }
    mysql_close();
    
    echo("csv uploaded");  
    ?>
    PHP:
    When I received an error, I added the .$q to the mysql_query so that I can see what the query is outputting. what i saw was instead of it returning the values as each column in the first row, it returned values as each row in just column one. ie: INSERT INTO test (SKU,Options,Option_Value,Subvalue) VALUES (SKU,0013,0015BZ,0016CB) each of the values in VALUES is the first item of a new line (ie:in excel, a1, a2, a3, a4...)

    PS: does anyone know how this will this work with duplicates? ie: if i upload file test2.csv and then upload it again with the same sku's but the options change, will it just insert the skus again or will it look for the sku and see if it exists, and then if it does update it or if it doesnt insert it...thanks
     
    jgarite, Jan 4, 2010 IP
  2. javaongsan

    javaongsan Well-Known Member

    Messages:
    1,054
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #2
    are you missing quotes?
    $values = implode("','",$data[$i]);
    Code (markup):
     
    javaongsan, Jan 4, 2010 IP