user1509201
user1509201

Reputation: 99

php import csv file into database

I have a file which I need to import into my database but I like to import 10 record at a time.

e.g. I have 100 records in my .csv file so first time it runs it will start from 0 then it will goto 10 and changes the your to domain.com/importfile.php/?start=10

this is the code I use.

$file = fopen($file, "r");
    while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
        $county = new County();
        $county->countrycode = $countrycode;
        $county->code = trim($data[0]);
        $county->var_name = $county->mod_write_check( trim($data[1]) );
        $county->name = trim($data[1]);
        $county->statecode = trim($data[2]);
        $save = $county->save();
    }
    fclose($file);

I would like to know if this can be done.

Upvotes: 1

Views: 805

Answers (2)

Putr
Putr

Reputation: 967

I would recommend using SplFileObject for deailing with files.

Here's a blog that goes thrugh the basics:

http://hakre.wordpress.com/2010/07/25/parsing-csv-files-with-php-spl-style/

The SplFileObject can easily seek but in combination with limitIterator you can also do:

$csv = new SplFileObject('data.csv');
$csv->setFlags(SplFileObject::READ_CSV);

foreach(new LimitIterator($csv, 0, 500) as $line){
  #save $line
}

Code snippet source

Upvotes: 1

oscar.getstring
oscar.getstring

Reputation: 54

You could use $seek = ftell($file); ftell documentation and fseek($file, $seek+1) you will need to carry in your session or somewhere else the value of $seek

Upvotes: 1

Related Questions