0

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?

3
  • Check if $name is empty, and don't INSERT if it is Commented Nov 8, 2014 at 15:51
  • 1
    You could simple use while(($rr = fgetcsv($file)) !== false) instead – fgetcsv will return false when it has reached the end of the file. Commented Nov 8, 2014 at 15:56
  • 1
    Instead of manual fgetcsving, use a SplFileObject foreach with ::READ_CSV and ::SKIP_EMPTY rather. Commented Nov 8, 2014 at 15:56

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.