duanou2016 2014-11-08 15:49
浏览 63


I'm using the following code in PHP to read a CSV file:

  $file = fopen("customers.csv", "r");

  while (!feof($file))
    $rr = fgetcsv($file);
    $name = $rr[0];
    $surname = $rr[1];

    $sql = 'INSERT INTO customer SET ...';

The code will insert all the records in the CSV file into customer table, but it tries to insert one line more with NULL values and fails.

How would you correct the code to insert only the number of lines that are in the customers.csv file?

  • 写回答

1条回答 默认 最新

  • douxie3625 2014-11-08 15:53

    The fgetcsv function will encounter EOF, but you do not exit the loop immediately. Instead you process the row of CSV as normal before checking for EOF in the while condition. Simply add a check for EOF immediately after the call to fgetcsv (and also in the while loop perhaps). But you could also do while (true) {...} and then 'exit' the while loop when you encounter EOF (or if $rr is empty) immediately after fgetcsv function. (Not sure of the php syntax, otherwise I would post exact code, but this logic should work)

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



  • ¥15 maccms影视模板 制作影视网站失败 求
  • ¥15 stm32按键设置闹钟数进退位不正常
  • ¥15 三电平逆变器中点电位平衡问题
  • ¥20 这怎么写啊 java课设
  • ¥15 用C语言完成一个复杂的游戏
  • ¥15 如何批量更改很多个文件夹里的文件名中包含文件夹名?
  • ¥50 MTK手机模拟HID鼠标出现卡顿
  • ¥20 求下下面这个数据结构代码
  • ¥20 前端 二进制文件流图片转化异常
  • ¥15 github上的这个C语言项目如何跑起来