我目前能够将CSV中的一行数据添加到数据库中,但我无法添加下一行和下一行。
我只是在问为什么只有一行插入到数据库中并且是一个修复程序会使所有行开始插入数据库?
以下代码:
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);
答案 0 :(得分:0)
您正在使用$ header将值映射到$ fields顺序,因此您的插入应包含$ fields顺序的字段而不是$ header order。
mysql_query("INSERT INTO csv (" . implode(',', $fields) . ") VALUES ('" . implode("','", $values) . "')");
同样最好清理数据以确保它被正确转义。
$values = array_map("mysql_real_escape_string", $values);
在你的mysql_query调用之前应该这样做。
此外,您不会在每次迭代时重新初始化$ value,因此在插入第2行时,您将获得第1行+第2行的字段。
所以打开你的while语句后
$values = array();
重新初始化。