在我的一个应用程序中,用户可以上传CSV文件(|分隔字段),上传后,我将文件的所有内容存储在临时表中(每次新上传时,我都会截断此表,使其包含当前文件数据)。之后,我对该表的每一行进行迭代,并根据业务逻辑执行一些数据库操作。
以下代码将对此进行说明:
if(isset($_POST['btn_uploadcsv']))
{
$filename = $_FILES["csvupload"]["name"];
$uploads_dir = 'csvs'; //csv files...
$tmp_name = $_FILES["csvupload"]["tmp_name"];
$name = time();
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$csvpath = "$uploads_dir/$name";
$row = 0;
$emptysql = "TRUNCATE TABLE `temp`";
$connector->query($emptysql);
if (($handle = fopen($csvpath, "r")) !== FALSE) {
$str_ins = "";
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
/*
* Here I am getting the column values to be store in the
* the table, using INSERT command
*/
unset($data);
}
fclose($handle);
}
/*Here I am selecting above stored data using SELECT statement */
for($j=0;$j<count($allrecords);$j++)
{
echo "In the loop";
/*If I use echo statement for debugging it is working fine*/
//set_time_limit(300);
/* I have tried this also but it is not working*/
if(!empty($allrecords[$j]['catid']))
{
// Here is my business logic which mailny deals with
// conditional DB operation
}
echo "Iteration done.";
/*If I use echo statement for debugging it is working fine*/
}
}
问题是当我在服务器上执行这个脚本时,它会给服务器超时错误。但当我在本地主机上测试上述脚本时,is运行良好。
同样如代码中所述,如果我使用echo
语句进行调试,那么它工作正常,当我删除它时,它开始出现连接超时问题。
我试过set_time_limit(300)
、set_time_limit(0)
,但似乎都不起作用。
任何想法,我该如何解决上述问题。
--非常感谢您抽出时间。
编辑:
我已经检查过了,文件正在上传到服务器上。
set_time_limit
更改为
ini_set("max_execution_time",300);
当php.ini中未设置max_execution_time时,set_time_limit有效。
我已经使用flush解决了这个问题,在后台执行查询时,将中间输出发送到浏览器。
这就是我修改代码的方式:
for($j=0;$j<count($allrecords);$j++)
{
/*At the end of each iteration, I have added the following code*/
echo " ";
flush();
}
感谢这个链接上的贡献者PHP:可能在等待数据库查询执行时将输出滴入浏览器?,从那里我得到了灵感。