The goal is that I would like to cycle through ALL of the .CSV files in my directory and run this script for each file so it appends the data into the DB. The issue stems from when I insert the loop below. I have compiled a PHP script that works perfectly when it comes to reading a SINGLE .CSV file into my MySQL DB. Despite this, I get the following error when I call the mysql_query function after inserting the import script into a loop: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
//CLEAR old contents from table
$queryDelete = "delete from $databasetable;";
$resultDelete = @mysql_query($queryDelete) or die("Error clearing table of old data: $query<br />" . mysql_error());
//READ directory for CSV files
//path to directory to scan IF NOT IN SAME FOLDER
$directory = "../data/";
//get all files IN CURRENT DIRECTORY with a .csv extension OTHERWISE add $csvfiles = glob($directory . "*.csv");
$csvfiles = glob("*.csv");
$numCSVFiles = count($csvfiles);
//Grab each CSV file and import to DB
for ($i = 0; $i < $numCSVFiles; $i++) {
$csvfile = $csvfiles[$i];
//TEST FILES
if(!file_exists($csvfile)) {
echo "File (" . $csvfile . ") not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
//$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto == 1)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n<br />";
//THIS IS WHERE THE ERROR OCCURS WHILE RUNNING INSIDE THE LOOP
$result = @mysql_query($query) or die("Error 1: " . mysql_error() . "<br />Query Attempted: " . $query);
if(!$result) { $resultText = "Failure to execute MySQL queries. Please try again later."; } else { $resultText = "Successfully executed queries."; }
}
@mysql_close($con) or die("Error 2: " . mysql_error());
//LOG mysql queries
if($save) {
if(!is_writable($outputfile)) {
echo "File is not writable, check permissions.\n";
}
else {
$file2 = fopen($outputfile,"w");
if(!$file2) {
echo "Error writing to the output file.\n";
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}
}
}
@
on the calls. – Lightness Races in Orbit Jul 21 '11 at 15:52