xralf
xralf

Reputation: 3632

Reading one more line when parsing CSV in PHP

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 ...';
    ...
    $s->execute();
  }
  fclose($file);

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?

Upvotes: 0

Views: 121

Answers (1)

Grantly
Grantly

Reputation: 2556

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)

Upvotes: 1

Related Questions