PHP import csv to MySQL database

Source: Internet
Author: User
Copy Code

2, Execution page insertdb.php

  1. Session_Start ();

  2. Header ("Content-type:text/html;charset:utf-8");

  3. Global variables

  4. $file =$_files[' filename ';
  5. $max _size= "2000000"; Maximum file limit (in bytes)
  6. $fname = $file [' name '];
  7. $ftype =strtolower (substr (STRRCHR ($fname, '. '), 1));
  8. File format
  9. $uploadfile = $file [' Tmp_name '];
  10. if ($_server[' Request_method ']== ' POST ') {
  11. if (Is_uploaded_file ($uploadfile)) {
  12. if ($file [' Size ']> $max _size) {
  13. echo "Import file is too large";
  14. Exit
  15. }
  16. if ($ftype! = ' csv ') {
  17. echo "Import file type is error";
  18. Exit
  19. }
  20. }else{
  21. echo "The file is not empty!";
  22. Exit
  23. }
  24. }

  25. Require ("./conn.php"); Connect to MySQL Database

  26. $row = 0;
  27. $filename = $file [' Tmp_name '];
  28. $handle =fopen ($filename, ' R ');
  29. while (!feof ($handle) && $data =fgetcsv ($handle, 1000, ', ')) {
  30. $arr _result=array ();
  31. if ($row ==0) {
  32. $row + +;
  33. Continue
  34. }
  35. if ($row >0 &&!empty ($data)) {
  36. $num =count ($data);
  37. for ($i =0; $i < $num; $i + +) {
  38. Array_push ($arr _result, $data [$i]);
  39. }

  40. $name = Iconv (' gb2312 ', ' utf-8 ', $arr _result[1]);

  41. $sex = Iconv (' gb2312 ', ' utf-8 ', $arr _result[2]);
  42. $sql = "INSERT into student (typeid,name,sex,age) value ($arr _result[0], ' $name ', ' $sex ', $arr _result[3])";
  43. Echo $sql;
  44. mysql_query ("Set names UTF8");
  45. $result =mysql_query ($sql);
  46. if ($result) {
  47. echo "INSERT success!!! ";
  48. }else{
  49. echo "Insert failed!!! ";
  50. }
  51. }
  52. $row + +;
  53. }
  54. Fclose ($handle);
  55. ?>

Copy Code
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.