Your check is here:
while (($line_of_data = fgetcsv($file_handle, 1000, ",")) !== FALSE)
First, you don’t need the !== FALSE
. It can just be this:
while (($line_of_data = fgetcsv($file_handle, 1000, ",")))
Also, your code is just checking while
that fgetcsv
is not empty. So what if there is an empty line in the file? It gets run twice. So how about this:
while (($line_of_data = trim(fgetcsv($file_handle, 1000, ",")))) {
if (!empty($line_of_data)) {
$stmt->execute(array(':field1' => $line_of_data [0], ':field2' => $line_of_data[1], ':field3' => $line_of_data[2]));
}
}
The idea is that when you call fgetcsv
let’s trim the line to get rid of extra stuff like maybe a line break at the end of the line. Then the if (!empty($line_of_data)) {
checks if the line is not empty & only acts on the query if it is definitely not empty. If somehow trim(fgetcsv(…))
doesn’t work, you can do it this way instead:
while (($line_of_data = fgetcsv($file_handle, 1000, ","))) {
if (!empty(trim($line_of_data))) {
$stmt->execute(array(':field1' => $line_of_data [0], ':field2' => $line_of_data[1], ':field3' => $line_of_data[2]));
}
}
With all of that logic in if (!empty(trim($line_of_data))) {
.