PHP Getting files in a directory

At first, this might be a silly question for some, but since I'm new to this, I'm still learning when I study. So here's my question:

I am trying to get all the files in a directory so that I can insert its contents into the database. I am currently using localhost. Using glob () I got what I needed. But here's where I have a problem. Since the glob () function returns an arraylist of filenames, how can I get the filename that is currently being read and insert it into the database table as well?

Here's my current w / c code that I got from this site :

$dir = "MyFiles/";
$curFile = glob($dir."*.csv");


foreach ($curFile as $filename) {
   $handle = fopen($filename,"r");
   }
   //loop through the file
   do{
      if ($data[0]) {
         mysql_query (" INSERT INTO tblCoordinates (id,filename,lat,lon)
         VALUES
         ('',
          '.$filename.',
          '".addslashes($data[0])."',
          '".addslashes($data[1])."')
         ");

   } while ($data = fgetcsv ($handle,1000,",","'"));
} 

      

Again, I also need the names of the files to be inserted into the database, but with my current code, the file name is not inserted.

+3


source to share


2 answers


Just noticed: Your statement '.$filename.'

is wrong. It should be '$filename'

...

You must first compile the sql command and then execute it as a single statement like this:

$glob=glob($dir."*.csv");
foreach ($glob as $filename) {
  $handle = fopen($filename,"r");
  while ($da = fgetcsv ($handle,1000,",","'")) {
    if ($da[0]) $data[]="('','$filename','".JOIN("','",array_slice($da,0,2))."')";
  }
} 
$mysql="INSERT INTO tblCoordinates (id,filename,lat,lon)  VALUES\n".JOIN(",\n",$data);
// echo $mysql // --> check it first ...
mysql_query($mysql);

      

Running my data in $dir='./'

, echo

gave me this



INSERT INTO tblCoordinates (id,filename,lat,lon)  VALUES 
('','./dat.csv','1','23'),
('','./dat.csv','2','27'),
('','./dat.csv','3','31'),
('','./dat.csv','4','35'),
('','./dat.csv','5','39')

      

What does your operator look like and - and most importantly - your error message?


(And of course: the function is mysql_query()

deprecated, use mysqli_query()

instead ...)

+1


source


I don't think you should use this approach. You can (and probably will) kill your database every time you run the script (especially if you have many files in that directory and many lines in each csv file). It would seem better to prepare a transaction, one insert with many values, and then commit. This way, you can also easily repeat the request to make sure everything is in order.

Note that you have to check if filename is a file or directory (I'm not sure, and .., but you may need to check this as well)



Also, I would recommend doing something like

$someVar = glob($dir."*.csv");
foreach($someVar as $filename) {
    // your code here
}

      

+2


source







All Articles