这篇文章主要为大家详细介绍了PHP 使用文件方式导入导出整个MYSQL数据库的实现方法,具有一定的参考价值,可以用来参考一下。
PHP mysql以文件形式导入导出整个数据库,感兴趣的小伙伴,下面一起跟随四海网的小编罗X来看看吧。
<?php
/**
* 文件方式导入导出整个MYSQL数据库
*
* @param 使用时一定要注意是否是处于导入状态,如果是导入操作,一定要先备份数据库,否则数据会被清空。。
* @author 四海网 www.q1010.com
**/
/*
导出
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();
?>
/*** 来自四海网(www.q1010.com) ***/
本文来自:http://www.q1010.com/173/202-0.html
注:关于PHP 使用文件方式导入导出整个MYSQL数据库的实现方法的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:数据库
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。