我有一个PHP脚本文件,可以将一系列CSV文件加载到MYSQL数据库中。
当我从命令行运行脚本一切顺利但是当我从浏览器运行它时它退出中间(大约65000条记录之后)和4个文件。
<?
if (isset($argv))
{
$_GET['load_date'] = $argv[1];
}
LoadFile('file1.csv');
LoadFile('file2.csv');
LoadFile('file3.csv');
LoadFile('file4.csv');
LoadFile('file5.csv');
LoadFile('file6.csv');
LoadFile('file7.csv');
function LoadFile($File_Name)
{
//global $serverinfo, $username, $password, $database, $dir_path, $dir_env;
include("datacon.inc.php");
mysql_connect($serverinfo, $username, $password);
@mysql_select_db($database) or die("Unable to select database");
//check if the file is existed
if (file_exists($File_Name) == FALSE) {
ECHO "<FONT COLOR=\"red\"> <b> " . $File_Name . " wasn't found </b> </FONT> <br>";
return;
} else {
ECHO $File_Name . " was found, start loading...<br>";
}
//Import uploaded file to Database
$file_handle = fopen($File_Name, "r");
while (($line_of_data = fgetcsv($file_handle, 0, ",", "\"", "\r\n")) !== FALSE) {
$line_import_query = "INSERT STATEMENT...";
//echo $line_import_query . "<BR><br>";
mysql_query($line_import_query) or die(mysql_error());
}
$Count_records_query =
"SELECT COUNT(*) AS COUNTS FROM `" . $database . "`.`TBL_TABLE`";
$Count_records_query_result = mysql_query($Count_records_query);
$Count_records = mysql_result($Count_records_query_result, 0, "COUNTS");
if ($Count_records <= 0) {
mysql_close();
echo "No records were loaded on " . $File_Name . ", somthing is wrong, check the file location/structure <br>";
} else {
echo "<FONT COLOR=\"red\"> <b> " . $File_Name . " were inserted </b> </FONT> <br>";
# Disconnect from the database.
}
fclose($File_Name, "r");
// close the connection
mysql_close();
return;
}
echo "Disconnected from database successfully! <br><br>
<input type=\"Button\" value=\"Ok, Finished! Back\" onclick=\"history.back()\">";
?>
怎么了?我该怎么调试呢?
答案 0 :(得分:3)
由于您使用的是IIS服务器,因此这是一个超时问题。整个过程的最长执行时间为30秒,并且php.ini中的max_execution_time
或php代码中的set_time_limit()
被忽略。
在Apache服务器下,30秒仅用于脚本执行; IO(文件读取,SQL请求,...)使用的时间将被扣除。
但是在php.ini中更改max_execution_time
并不是一个好主意,因为这会影响所有的php线程,并且由于许多请求在超时到期之前仍然保持打开状态,因此可能会使服务器超载。
例外情况下,您可以在PHP代码中使用set_time_limit();
在本地更改此设置
另一种解决方案是使用页面刷新来划分流程。
在此示例中,文件为“LoadCSV.php”(在标题命令中使用)
If (isset($_SESSION['ProcessId'])){ // process Phase
$P=$_SESSION['ProcessId'];
LoadFile($_SESSION['ProcessArray'][$P]); //All echo must be removed from LoadFile !!!
$P+=1;
if ($P<(count($_SESSION['ProcessArray'])-1)){
header('location: LoadCSV.php?Action=ImportFiles');
}
else{ // end Phase
unset($_SESSION['ProcessArray']);
unset($_SESSION['ProcessId']);
echo 'Finished';
}
}
else{ // Init Phase
$LoadArray=array(
'file1.csv',
'file2.csv',
'file3.csv',
'file4.csv',
'file5.csv',
'file6.csv',
'file7.csv'
);
$_SESSION['ProcessArray']=$LoadArray;
$_SESSION['ProcessId']=0;
header('location: LoadCSV.php?Action=ImportFiles');
}
答案 1 :(得分:0)
尝试ini_set('max_execution_time', 0);
将php脚本设置为运行直到完成。