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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入