Question

This is the first line of my CSV (answer.csv):

Respondent Name,name,1

I am using the following code to parse and insert it into a db

if (($handle = fopen("answer.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo $num;
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;

    $query_add="INSERT INTO  answer (`AnswerValue`,`AnswerKey` ,`Question`)
    VALUES ($data[0],$data[1],$data[2])";
    echo $query_add;
    echo mysql_query($query_add) or die(mysql_error());
    #for ($c=0; $c < $num; $c++) {
    #    echo $data[$c] . "<br />\n";
    #}
  }
  fclose($handle);
  }

However, I get the following error because the line is not being parsed by ",":

Ouput :

1 fields in line 1: 

Respondent Name name    1

    INSERT INTO answer (`AnswerValue`,`AnswerKey` ,`Question`) 
       VALUES (Respondent Name  name    1,,)

You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right
syntax to use near 'Name    name 1,,)' at line 2

For some reason, it shows there is only one field in line 1 whereas there are 3 fields if we look at the csv file...

Anyone knows why?

Was it helpful?

Solution 2

you must put the values in the quotes.

try this :

$query_add="INSERT INTO  answer (`AnswerValue`,`AnswerKey` ,`Question`)
    VALUES ('".$data[0]."','".$data[1]."','".$data[2]."')";

and when I try your code, with my changes above,this is the result :

3

3 fields in line :
INSERT INTO answer (`AnswerValue`,`AnswerKey` ,`Question`) 
VALUES ('Respondent Name','name','1')

OTHER TIPS

Maybe your CSV file charset is invalid. Make sure it is encoded in UTF8.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top