Parse CSV with PHP send to DB

Discussion in 'PHP' started by timallard, May 24, 2009.

  1. timallard

    timallard Well-Known Member

    Messages:
    1,634
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    158
    #21
    OK this works....almost!!

    Works fine with my sample data,..when i switch it over to my 6,000 line csv, it goes through about 47 of them then stops and says Query was empty. do i need ot set a buffer somewhere? its a 2 meg csv

    This is my code..


    <?php
    include 'config/config-test.php';


    $handle = fopen("Declare.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 = sprintf("INSERT INTO curiosities (Curiosity, FirstName, LastName, Email, ZipCode, Town, Category) 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])."')");
    # Run the insert statement
    mysql_query($query) or die(mysql_error());
    # Get the member_id (auto increment column)
    }
    fclose($handle);

    ?>
     
    timallard, May 25, 2009 IP
  2. timallard

    timallard Well-Known Member

    Messages:
    1,634
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    158
    #22
    OK!!!! I GOT IT!!!!!!!!!!!!!!!!!!!!!

    I changed the query to: mysql_query() instead of sprintr.

    ugh. this was a beast. thank YOU ALL a huge amount.
     
    timallard, May 25, 2009 IP