user3201441
user3201441

Reputation: 167

Import multiple files using php

I am trying to import csv files in my table. Searching in the Internet, I have found a code which is working and that I modified based on my needs.

Unfortunately, it only works for a single file insertion. I have further tried to edit it, but it just inserts the last file that is in the directory. Any help will be much appreciated.

//get the csv file
    $dir = "Files/";
    $currentFile = glob($dir."*.csv");
    $counter = count($currentFile);

        foreach ( $currentFile as $filename) {
            $handle = fopen($filename,"r");
        }

        $file = basename($filename);
        //loop through the csv file and insert into database 
    do { 

        if ($data[0]) { 
            mysql_query("INSERT INTO tblCoordinates (gps_id,lat,lng,time,cmt,cnt,cty,str,cde,lnt,hgt,name) VALUES 
                ( 
                    '$file',
                    '".mysql_real_escape_string($data[0])."',
                    '".mysql_real_escape_string($data[1])."',
                    '".mysql_real_escape_string($data[2])."',
                    '".mysql_real_escape_string($data[3])."',
                    '".mysql_real_escape_string($data[4])."',
                    '".mysql_real_escape_string($data[5])."',
                    '".mysql_real_escape_string($data[6])."',
                    '".mysql_real_escape_string($data[7])."',
                    '".mysql_real_escape_string($data[8])."',
                    '".mysql_real_escape_string($data[9])."',
                    '".mysql_real_escape_string($data[10])."'
                ) 
            "); 
        } 
    } while ($data = fgetcsv($handle,1000,",","'")); 
    //

The $counter does say that I have 4 files in my $dir which is true and the filenames are "5729.csv", "4563.csv", "8718.csv", "4494.csv".

My problem: The code does insert but just the last file "4494.csv". How would I be able to insert all the files?

Upvotes: 1

Views: 1069

Answers (2)

MaggsWeb
MaggsWeb

Reputation: 3027

Your foreach loop is closing too early

foreach ( $currentFile as $filename) {
    $handle = fopen($filename,"r");

    // process your files here

} // close 'foreach'

Upvotes: 1

Oldskool
Oldskool

Reputation: 34837

Extend your foreach. Currently you're only assigning the $handle variable in your loop, but the do loop is outside of the foreach, thus it only renders the last file.

foreach ($currentFile as $filename) {
    // Your loop only keeps setting the $handle
    $handle = fopen($filename,"r");
}

// At this point, only the last entry from $currentFile is parsed

So it should be something like this:

foreach ($currentFile as $filename) {
    $handle = fopen($filename,"r");

    $file = basename($filename);

    //loop through the csv file and insert into database 
    do { 
        // Your parse logic here...
    } while ($data = fgetcsv($handle,1000,",","'")); 
} // foreach ends here

Upvotes: 0

Related Questions