I currently have been able to add one row of data from a CSV into the database but I am unable to add the next row and the next row.
I am simply asking why is it that only one row is being inserted into the database and is their a fix which would make all rows start inserting into the database?
Code Below:
include('config.php');
$file = "test.csv";
$separator = ",";
$length = 0; // size of the longest line(!), 0 = no limit
$fields = array('title', 'firstName', 'secondName', 'emailAddress', 'houseNumber', 'mobileNumber', 'address1', 'address2', 'address3', 'address4', 'postcode'); // use it as a white list
$handle = fopen($file, "r");
$header = array_flip(fgetcsv($handle, $length, $separator));
$values = array();
$i = 1;
while(($csvData = fgetcsv($handle, $length, $separator)) !== false){
echo $i." - You have inserted another row of data into the database.<br>";
foreach ($fields as $field){ // put all values in an array in correct order
$values[] = $csvData[$header[$field]];
}
mysql_query("INSERT INTO csv (" . implode(',', array_keys($header)) . ") VALUES ('" . implode("','", $values) . "')");
$i++;
}
fclose($handle);
You are using $header to map the values into $fields order so your insert should have the fields in $fields order instead of $header order.
mysql_query("INSERT INTO csv (" . implode(',', $fields) . ") VALUES ('" . implode("','", $values) . "')");
also it would be a good idea to sanitize the data to make sure it is properly escaped.
$values = array_map("mysql_real_escape_string", $values);
before your mysql_query call should do it.
Also you are not re initializing $values with each iteration so when inserting row 2 you get fields for row 1 + row 2.
so after you open your while statement do
$values = array();
to reinitialize it.