Home >Backend Development >PHP Tutorial >PHP imports large amounts of data into mysql (example)

PHP imports large amounts of data into mysql (example)

WBOY
WBOYOriginal
2016-07-25 08:54:581804browse
  1. //Fast Mysql big data backup

  2. //Before use, please first modify the SQL file name, database host name, database user name, and password to be imported according to the code comments ,Database name.
  3. //At the same time, ftp the database file and text into the website directory, and then access this file in WEB mode
  4. //edit: bbs.it-home.org
  5. $file_name="bn_site.sql";//To be imported SQL file name
  6. $dbhost="localhost";//Database host name
  7. $dbuser="root";//Database user name
  8. $dbpass="";//Database password
  9. $dbname="bn_site"; // Database name
  10. set_time_limit(0);//Set the timeout to 0, which means it will always be executed. When php is invalid in safe mode, the import will time out. At this time, it needs to be imported in sections
  11. $fp=@fopen($file_name,"r") or die ("Cannot open SQL file");//Open the file
  12. mysql_connect($dbhost,$dbuser,$dbpass) or die("Cannot connect to database"); //Connect to database
  13. mysql_select_db($dbname) or die("Cannot open database"); //Open database
  14. echo "is Execute import operation";
  15. while($SQL=GETNEXTSQL()){
  16. if(!mysql_query($sql)){
  17. echo "Execution error: ".mysql_error()."
    ";
  18. echo "The SQL statement is:
    ".$SQL."
    ";
  19. };

  20. }

  21. echo "Import completed ";

  22. fclose($fp) or die ("can"t close file $file"); //Close the file

  23. mysql_close();
  24. //From file Get SQL item by item in
  25. function GETNETSQL(){
  26. global $fp;
  27. $sql="";
  28. while( $line=@fgets($fp,40960)){
  29. $line=trim($line);
  30. / /The following three sentences are not needed in higher versions of PHP, but may need to be modified in some lower versions.
  31. $line = str_replace("\\","\",$line);
  32. $line = str_replace("'"," '",$line);
  33. $line = str_replace("\r\n",chr(13).chr(10),$line);
  34. if (strlen($line)>1){
  35. if ( $line[0]=="-"&& $line[1]=="-"){
  36. continue;
  37. }
  38. }

  39. $sql.=$line.chr(13 ).chr(10);

  40. if (strlen($line)>0){
  41. if ($line[strlen($line)-1]==";"){
  42. break;
  43. }
  44. }
  45. }
  46. return $sql;
  47. }
  48. ?>

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