Home  >  Article  >  Backend Development  >  PHP data batch import csv file (example)

PHP data batch import csv file (example)

WBOY
WBOYOriginal
2016-07-25 08:55:141107browse
  1. /**PHP imports csv files into the database ***

  2. * and calculates the program execution time at the same time
  3. ***/
  4. //Define the get time function
  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 ");//Connect to the database
  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 statement executed successfully!
    ";
  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 "Program execution time: ".$time."seconds";
  30. ?>

Copy Code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn