当前位置:首页 > PHP教程 > php应用 > 列表

PHP处理SQL脚本文件导入到MySQL的代码实例

发布:smiling 来源: PHP粉丝网  添加日期:2020-10-28 11:26:41 浏览: 评论:0 

通常在制作安装程式,数据备份程序的时候会要用到这样的代码,我看网上有是有不太多,而且有些也不是很好用,有时候这种代码直接用现成的可以节省很多时间,那么我就从stackoverflow转了一个过来,需要的朋友可以参考下。

  1. <?php 
  2.  
  3. // Name of the file 
  4. $filename = 'churc.sql'; 
  5. // MySQL host 
  6. $mysql_host = 'localhost'; 
  7. // MySQL username 
  8. $mysql_username = 'root'; 
  9. // MySQL password 
  10. $mysql_password = ''; 
  11. // Database name 
  12. $mysql_database = 'dump'; 
  13.  
  14. // Connect to MySQL server 
  15. mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error()); 
  16. // Select database 
  17. mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error()); 
  18.  
  19. // Temporary variable, used to store current query 
  20. $templine = ''; 
  21. // Read in entire file 
  22. $lines = file($filename); 
  23. // Loop through each line 
  24. foreach ($lines as $line) 
  25. { 
  26. // Skip it if it's a comment 
  27. if (substr($line, 0, 2) == '--' || $line == '') 
  28.     continue; 
  29.  
  30. // Add this line to the current segment 
  31. $templine .= $line; 
  32. // If it has a semicolon at the end, it's the end of the query 
  33. if (substr(trim($line), -1, 1) == ';') 
  34. { 
  35.     // Perform the query 
  36.     mysql_query($templine) or print('Error performing query \'&lt;strong&gt;' . $templine . '\': ' . mysql_error() . '&lt;br /&gt;&lt;br /&gt;'); 
  37.     // Reset temp variable to empty 
  38.     $templine = ''; 
  39. } 
  40. } 
  41.  echo "Tables imported successfully"; 
  42. ?> 

Tags: PHP处理SQL导入

分享到: