我的目标是循环浏览目录中的所有.CSV文件,并为每个文件运行此脚本,以便将数据附加到数据库中。问题源于我在下面插入循环时。我已经编译了一个PHP脚本,在将MySQL.CSV文件读入我的MySQL数据库时非常有效。尽管如此,在将导入脚本插入循环后调用mysql_query函数时出现以下错误:无法通过socket'/tmp/mysql.sock'连接到本地MySQL服务器(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);
}
}
}
}
答案 0 :(得分:3)
您正在执行mysql_close()
INSIDE循环,因此在插入第一个文件后,您将终止数据库连接,然后尝试插入下一个文件。
如果你的代码正确缩进,你就会看到这个问题。
答案 1 :(得分:1)
您正在关闭循环内的数据库连接。如果要继续使用它,请不要关闭连接。
答案 2 :(得分:0)
我认为你错过了一个结束的大括号{
......
mysql_close()
过早被调用:它在for ($i = 0; $i < $numCSVFiles; $i++)
循环中被调用。