0

I managed to import file from US.txt to places table and all seems ok, except that only rows from even numbers in file are being imported. Instead of 40975 rows I have 20487. I tried with while loop(fread, fgetcsv, fgets, feof methods), for loop with 40975 iterations(btw. which isn't working at all). I tried to print the output in console with similar file containing only few rows but output is even weirder. I'm out of ideas to solve this.

#!/usr/bin/env php
<?php
    require("../includes/config.php");

    $argv;

    // open file
    $file = fopen($argv[1], "r");
    // error handling (http://stackoverflow.com/questions/24753821/php-fopen-error-handling)
    if (!file_exists($argv[1]))
    {
        throw new Exception('File not found.');
    }
    if (!$file)
    {
        throw new Exception('File open failed.');
    }  

    // read every line
    while(fgetcsv($file,  500, "\t")) 
    {
        $csvarray = [];
        $csvarray = fgetcsv($file,  500, "\t"); // enclosure optional 4th argument deleted

        CS50::query("INSERT INTO places(country_code, postal_code, place_name, admin_name1, admin_code1, admin_name2, admin_code2, admin_name3, admin_code3, latitude, longitude, accuracy) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", $csvarray[0], $csvarray[1], $csvarray[2], $csvarray[3], $csvarray[4], $csvarray[5], $csvarray[6], $csvarray[7], $csvarray[8], $csvarray[9], $csvarray[10], $csvarray[11]);
    }

    // close file
    fclose($file);
?>

1 Answer 1

2

This while(fgetcsv($file, 500, "\t")) is reading the odd numbered lines. This $csvarray = fgetcsv($file, 500, "\t"); is reading the even numbered lines, which are then inserted into the db.

3
  • Reminds me of the common error in pset4 recover. (beat me to the punch by 30 seconds. :-P )
    – Cliff B
    Commented Dec 19, 2016 at 23:50
  • That was it. I used 'for' loop once again and it works. I don't know how I used it earlier that it doesn't. Commented Dec 20, 2016 at 10:20
  • It might have been something like while($cvsarray = fgetcsv($file, 500, "\t")), and then eliminating the second fgetcsv. Commented Dec 20, 2016 at 11:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .