Loop Through A CSV Starting at ROW....X

Discussion in 'PHP' started by timallard, Aug 10, 2009.

  1. #1
    Hello,

    I have a script that takes a csv and uploads it row by row into my DB.
    This CSV file gets updated often, and many new rows get appended to the end of it.

    Upon uploading a file, I would like to store a number in my DB marking the last row number it uploaded.

    How can I start my next upload to start at that last row number?

    E.x.

    I upload my CSV and 100 new rows get added to my DB. I insert in the config table a row marking the number "100".

    The next time I try to upload my CSV, it looks at the config, looks for the number and resumes at row 101.

    here is the code I am using to loop through the CSV.



    $handle = fopen("Declare123.csv", "r");
    while (!feof($handle))
    {
    // grab one line of data
    $data = fgets($handle);
    // trim the newline from end of line
    $data = trim($data);
    // put fields into array separated by ," (comma, quote), this still leaves a trailing quote that we have to get rid of
    $fields = explode(',"', $data);

    // trim the trailing quote and echo the fields
    for ($i=0; $i<sizeof($fields); $i++)
    {
    $fields[$i] = rtrim($fields[$i], '"');
    $fields[$i] = ltrim($fields[$i], '"');
    echo 'fields['. $i . ']: ' . $fields[$i] . '<br />';



    }
    $query = mysql_query("INSERT INTO curiosities (Curiosity, FirstName, LastName, Email, ZipCode, Town, Category, DateStamp) VALUES ('".mysql_real_escape_string($fields[0])."','".mysql_real_escape_string($fields[1])."','".mysql_real_escape_string($fields[2])."','".mysql_real_escape_string($fields[3])."','".mysql_real_escape_string($fields[4])."','".mysql_real_escape_string($fields[5])."','".mysql_real_escape_string($fields[6])."','".mysql_real_escape_string($fields[13])."')") or die(mysql_error());
    # Get the member_id (auto increment column)
    }
    fclose($handle);



    Any ideas on how to get it to resume at a certain row?

    ----------------------------------------


    Thank You!
     
    timallard, Aug 10, 2009 IP
  2. Aces A

    Aces A Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Here is what I use:

    
    $fcontents = file ('./data.txt');  // expects the csv file to be in the same dir as this script
    	
    for($i=1; $i<sizeof($fcontents); $i++) {           // i starts at 1 because there is table header in the first row
    	$line = addslashes(trim($fcontents[$i])); 
    	$arr = explode("\t", $line); 
    	//if your data is comma separated
    	// instead of tab separated, 
            // change the '\t' above to ',' 
    		
    	$sql = "INSERT into ... values(' " . implode("','", $arr) . ")";
            executeQuery($sql);
    }
    
    Code (markup):
    Initialize $i to be at your start row instead of 1, and this should work.
     
    Aces A, Aug 10, 2009 IP