PHP 使用文件方式导入导出整个MYSQL数据库的实现方法

前端之家收集整理的这篇文章主要介绍了PHP 使用文件方式导入导出整个MYSQL数据库的实现方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP MysqL文件形式导入导出整个数据库,感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:

<?PHP
/**
 * 文件方式导入导出整个MysqL数据库
 *
 * @param 使用时一定要注意是否是处于导入状态,如果是导入操作,一定要先备份数据库,否则数据会被清空。。
 * @author 编程之家 jb51.cc jb51.cc
 **/
/* 
导出
SELECT * INTO OUTFILE 'c:/name.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\''
LINES TERMINATED BY '\n'
FROM zones;
导入
LOAD DATA INFILE 'c:/name.txt' INTO TABLE zones  
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\''
LINES TERMINATED BY '\n';
*/ 
set_time_limit(0);
define(HOST,'127.0.0.1');
define(USER,'root');
define(PWD,'');
define(DBNAME,'test');
define(DIR,'E:/www/MysqL_data/');
//0为导入 1为导出 2为修复 
define(OPERATION,1);
MysqL_connect(HOST,USER,PWD) or
die("Could not connect: " . MysqL_error());
MysqL_select_db(DBNAME) or
die("Could not select db: " . MysqL_error());
$result = MysqL_query("show tables");
if(!is_dir(DIR)){
 die('Folder does not exist');
}
if(OPERATION==0){
 //前提:需要先前导入表结构
 //导出命令:MysqLdump -u root -p -d test>test.sql
 while ($row = MysqL_fetch_array($result,MysqL_NUM)) {
  $fileName=DIR.$row[0].".txt";
  if(file_exists($fileName)){
   //delete  truncate
   $querysql='TRUNCATE TABLE `'.$row[0].'`';
   MysqL_query($querysql) or
   die("Could not truncate table: ". $querysql . MysqL_error());
   
   $querysql = "LOAD DATA INFILE '".$fileName."' 
   INTO TABLE `".$row[0]."`
   FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\''
   LINES TERMINATED BY '\n'";
   MysqL_query($querysql) or
   die("Could not insert into table: ". $querysql . MysqL_error());
   echo 'insert into table '.$row[0].' success.<br/>';
  }else{
   echo 'Not insert into table '.$row[0].'<br/>';
  }
 }
 echo "The task is finished";
}else if(OPERATION==1){
 if (is_writable(DIR)) {
  while ($row = MysqL_fetch_array($result,MysqL_NUM)) {
   $fileName=DIR.$row[0].".txt";
   if(file_exists($fileName)){
    unlink($fileName);
   }
   $querysql = "SELECT * INTO OUTFILE '".$fileName."'
   FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\''
   LINES TERMINATED BY '\n' 
   FROM `".$row[0]."`";
   MysqL_query($querysql) or
   die("Could not dump table: ". $querysql . MysqL_error());
   echo 'dump table '.$row[0].' success.<br/>'; 
  }
  echo "The task is finished";
 }else{
  echo 'Folder '.DIR.' can not writeable';
 }
}else if(OPERATION==2){
 while ($row = MysqL_fetch_array($result,MysqL_NUM)) {
  $fileName=DIR.$row[0].".txt";
  if(file_exists($fileName)){
   unlink($fileName);
  }
  $querysql = "REPAIR TABLE `$row[0]`";
  MysqL_query($querysql) or
  die("Could not repair table: ". $querysql . MysqL_error());
  echo 'repair table '.$row[0].' success.<br/>'; 
 }
}
MysqL_free_result($result);
MysqL_close();
?>


/***   来自编程之家 jb51.cc(jb51.cc)   ***/

猜你在找的PHP相关文章