PHP需要花费大量时间在MySQL中插入数据

时间:2014-11-12 06:25:58

标签: php mysql

我正在使用此代码使用PHP在MySQL中插入csv文件。即使文件只有20条记录,它也会很好地插入,但需要30秒才能完成。我可以在MySQL中看到记录已上传,但仍会在网页上显示加载。请帮我找出错误。

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("sg",$con);

define('CSV_PATH','C:/Users/mkutbudd/Desktop/');
$csv_file = CSV_PATH . $_POST['name'];

if (($getfile = fopen($csv_file, "r")) !== FALSE) { 
   $data = fgetcsv($getfile, 1000, ",");
   while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
      $num = count($data); 
      for ($c=0; $c < 1; $c++) {
         $result = $data; 
         $str = implode(",", $result); 
         $slice = explode(",", $str);
         $col1 = $slice[0]; 
         $col2 = $slice[1];

         $query = "INSERT INTO dummy(DeclarationNo,dum3) VALUES('".$col1."','".$col2."')";
         $s=mysql_query($query, $con ); 
      }
   } 
}
echo "File data successfully imported to database!!";
echo "<script type='text/javascript'>window.location=\"fetch22.php\";</script>";
mysql_close($con); 
?>

2 个答案:

答案 0 :(得分:0)

检查我的下面的脚本,

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("sg",$con);

define('CSV_PATH','C:/Users/mkutbudd/Desktop/');
$csv_file = CSV_PATH . $_POST['name'];

if (($getfile = fopen($csv_file, "r")) !== FALSE) { 
   //$data = fgetcsv($getfile, 1000, ",");
   while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
      $num = count($data); 
      $row=array();
      for ($c=0; $c < $num; $c++) {
         $row[]=$data[$c];
      }

      $query = "INSERT INTO dummy(DeclarationNo,dum3) VALUES('".$row[0]."','".$row[1]."')";
      $s=mysql_query($query, $con ); 
   } 
}
echo "File data successfully imported to database!!";
echo "<script type='text/javascript'>window.location=\"fetch22.php\";</script>";
mysql_close($con); 
?>

我可以看到你的插入位置错误。如果存在任何拼写错误,请更正我的代码。

答案 1 :(得分:0)

首先,你不应该再使用mysql库了。去寻找mysqli或PDO。

作为您问题的答案,mysql中有一个函数LOAD DATA INFILE直接读取CSV文件。有关它的更多信息,请参见reference

带有丢弃行的引用示例:

LOAD DATA INFILE 'file.txt'
  INTO TABLE t1
  (column1, @dummy, column2, @dummy, column3);