First, this might be a stupid question for some but as I am a newbie to this, I am still learning while doing things. So here's my question :
I am trying to get all files in a directory so that I can insert its content to the database. I am currently using localhost. Using glob() function, I got what I need. But here's where I have a problem. Since glob() function returns an arraylist of filenames, how can I get the filename currently being read, and insert that also in the database table?
Here's my current code w/c 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 filenames to be inserted to the database, but with my current code, the filename is not inserted.
I do not think you should use this approach. You might (and probably will) kill your database every time you run the script (especially if you have many files in this directory and many line in each csv file). It would seem better to prepare a transaction, one insert with many values, then commit. That way, you will also be able to easily echo the query to see if everything is alright.
Note that you should check if filename is a file or a directory (I am not sure about . and .. but you might need to check that too)
Also, I would recommend doing something like
$someVar = glob($dir."*.csv");
foreach($someVar as $filename) {
// your code here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With