dongxun1142
2013-07-09 15:31
浏览 39
已采纳

从CSV中将多于一行插入mysql数据库时出现问题

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);
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dt97868 2013-07-09 15:39
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题