上传csv并在MySQL中导入数据

时间:2012-04-03 10:03:38

标签: php mysql

好的我想做的就是给用户一个简单的表格,他们可以上传包含票价的CSV文件。然后,数据应上传到数据库中。

这是代码......

<?php
 require_once('includes/connection.php');
 if(isset($_POST['submit']))
   {
     $filename=$_POST['filename'];
     $handle = fopen("$filename", "r");
     while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
     {

       $import="INSERT into fares_usa(cruise_id, active, type, category, placement, deck, fare, offered, status, sortorder)          values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]')";
       mysql_query($import, $connection) or die(mysql_error());
     }
     fclose($handle);
     print "Import done";
   }
   else
   {

      print "<form enctype='multipart/form-data' action='fileupload.php' method='POST'>";
      print "Select file to import:";
      print "<input type='file' name='filename' size='20'>";
      print "<input type='submit' name='submit' value='submit'></form>";
   }
   ?>

非常感谢任何帮助!

由于

Rich:)

1 个答案:

答案 0 :(得分:0)

您好像在使用$_POST而不是$_FILES

<?php
 require_once('includes/connection.php');
 if(isset($_POST['submit']))
   {
     $filename=$_FILES['filename']['tmp_name'];
     $handle = fopen("$filename", "r");
     while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
     {

       $import="INSERT into fares_usa(cruise_id, active, type, category, placement, deck, fare, offered, status, sortorder) 
       values('".mysql_real_escape_string($data[0])."',
       '".mysql_real_escape_string($data[1])."',
       '".mysql_real_escape_string($data[2])."',
       '".mysql_real_escape_string($data[3])."',
       '".mysql_real_escape_string($data[4])."',
       '".mysql_real_escape_string($data[5])."',
       '".mysql_real_escape_string($data[6])."',
       '".mysql_real_escape_string($data[7])."',
       '".mysql_real_escape_string($data[8])."',
       '".mysql_real_escape_string($data[9])."')";
       mysql_query($import, $connection) or die(mysql_error());
     }
     fclose($handle);
     print "Import done";
   }
   else
   {

      print "<form enctype='multipart/form-data' action='fileupload.php' method='POST'>";
      print "Select file to import:";
      print "<input type='file' name='filename' size='20'>";
      print "<input type='submit' name='submit' value='submit'></form>";
   }
   ?>

还添加mysql_real_escape_string以在将输入添加到数据库之前转义输入。这是您应该为用户输入做的最小“清理”。