php把csv文件导入到mysql数据库

本程序实现数据导入原理是先把csv文件上传到服务器,然后再通过php的fopen与fgetcsv文件把数据保存到数组,然后再用while把数据一条条插入到mysql数据库,代码如下:

  1. $fname = $_files['myfile']['name'];
  2. $do = copy($_files['myfile']['tmp_name'],$fname);
  3. if ($do){
  4. echo"导入数据成功<br>";
  5. }else{
  6. echo "";
  7. }
  8. error_reporting(0);// 导入csv格式的文件
  9. $connect=mysql_connect("localhost","root","") or die("could not connect to database");
  10. mysql_select_db("gklqtzcx",$connect) or die (mysql_error());
  11. mysql_query("set names 'gbk'");
  12. $fname = $_files['myfile']['name'];
  13. $handle=fopen("$fname","r");
  14. while($data=fgetcsv($handle,10000,",")){
  15. $q="insert into records (name,classes,a_time,college,notify,receiver,r_time,handler) values ('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')";
  16. mysql_query($q) or die (mysql_error());
  17. }//开源代码phpfensi.com
  18. fclose($handle);
  19. echo "<meta http-equiv="refresh" content="1;url=list.php">1秒钟转入列表页,请稍等."
  20. ?>
  21. <form enctype="multipart/form-data" action="<?php echo"".$_server["php_self"].""; ?>" method="post">
  22. <p>导入cvs数据 <input name="myfile" type="file"> <input value="提交" type="submit">
  23. </p>
  24. </form>