当前位置:Gxlcms > PHP教程 > php数据批量导入csv文件(示例)

php数据批量导入csv文件(示例)

时间:2021-07-01 10:21:17 帮助过:50人阅读

  1. /**php导入csv文件到数据库***

  2. *同时计算程序执行时间
  3. ***/
  4. //定义获取时间函数
  5. function getmicrotime(){
  6. list($usec, $sec) = explode(" ",microtime());
  7. return ((float)$usec + (float)$sec);
  8. }

  9. $time_start = getmicrotime();

  10. include("db.inc.php");//连接数据库
  11. $db=new testcsv;

  12. $handle = fopen ("test.csv","r");

  13. $sql="insert into scores(idcard,names,num,sex,nation,score) values(\'";
  14. while ($data = fgetcsv ($handle, 1000, ",")) {
  15. $num = count ($data);
  16. for ($c=0; $c < $num; $c++) {
  17. if($c==$num-1){$sql=$sql.$data[$c]."\')";break;}
  18. $sql=$sql.$data[$c]."\',\'";
  19. }
  20. print "
    ";
  21. echo $sql."
    ";
  22. $db->query($sql);
  23. echo "SQL语句执行成功!
    ";
  24. $sql="insert into scores(idcard,names,num,sex,nation,score) values(\'";
  25. }
  26. fclose ($handle);
  27. $time_end = getmicrotime();
  28. $time = $time_end - $time_start;
  29. echo "程序执行时间:".$time."秒";
  30. ?>

人气教程排行