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?
$nameis empty, and don't INSERT if it iswhile(($rr = fgetcsv($file)) !== false)instead –fgetcsvwill returnfalsewhen it has reached the end of the file.fgetcsving, use aSplFileObjectforeach with ::READ_CSV and ::SKIP_EMPTY rather.