php 代码实现导入导出 mysql数据库
程序员文章站
2024-03-20 21:23:22
...
之前一直是手工导入导出数据库,在服务器端或者客户端备份还原数据库经常了出错,很不方便,现我写了一个关于php 代码实现 备份还原mysql数据库
<?php
class DbOperate {
public $db;
private $debug = false;
public $tbprefix = '';
public function __construct($mysql) {
global $db;
$this ->db = $mysql;
$this -> tbprefix = $tbprefix;
}
/**查询**/
function getAllTabName() {
$sql = "show tables";
$arrs = $this ->db -> query($sql);
$tab_arr = array();
while($row =$this ->db -> fetch_array($arrs)){
$tab_arr[] = $row['Tables_in_takoo_db'];
}
return $tab_arr;
}
/**备份**/
function bakupData($tb_arr,$start = 0,$sizelimit) {
global $sizelimit,$startfrom,$tbid,$rows,$stop;
$t_count = count($tb_arr);
for($i=0;$i<$t_count;$i++){
$res = $this -> db -> query("SHOW TABLE STATUS LIKE '$tb_arr[$i]'");
$arr = $this -> db -> fetch_array($res);
$rows = (int)$arr['Rows'];
$limitadd = "LIMIT $start,100000";
$query = $this -> db -> query("SELECT * FROM $tb_arr[$i]");//$limitadd
$num_F = mysql_num_fields($query);
while (FALSE!=$datadb = mysql_fetch_row($query)) {
$start++;
$table=$tb_arr[$i];
$bakupdata .= "INSERT INTO $table VALUES("."'".addslashes($datadb[0])."'";
$tempdb='';
for ($j=1;$j<$num_F;$j++) {
$tempdb .= ",'".addslashes($datadb[$j])."'";
}
$bakupdata .=$tempdb. ");\n";
if ($sizelimit && strlen($bakupdata)>$sizelimit*1000) {
break;
}
}
mysql_free_result($query);
if($start>=$rows) {
$start=0;
$rows=0;
}
$bakupdata .="\n";
if($sizelimit && strlen($bakupdata)>$sizelimit*1000){
$start==0 && $i++;
$stop=1;
break;
}
$start=0;
}
if($stop==1) {
$i++;
$tbid = $i;
$startfrom = $start;
$start = 0;
}
return $bakupdata;
}
/**备份表**/
public function bakupTable($tb_arr) {
$this -> db->query("SET SQL_QUOTE_SHOW_CREATE = 0");
foreach ($tb_arr as $table) {
$creattable.= "DROP TABLE IF EXISTS $table;\n";
$res = $this -> db -> query("SHOW CREATE TABLE $table");
$ctable = $this -> db -> fetch_array($res);
$creattable .= $ctable['Create Table'].";\n\n";
}
$bak = "#\n# Takoo: bakfile\n# Version: 1.1.2\n# Time: ".date('Y-m-d H:i:s')."\n# Type: ".count($tb_arr)." \n# 官方网站:: http://www.takoo.com.cn\n# --------------------------------------------------------\n\n\n";
return $bak.$creattable;
}
/**还原**/
public function bakInData($file) {
global $dbcharset;
$sql = file($file);
$query='';
$num=0;
foreach ($sql as $key => $value) {
$value = trim($value);
if (!$value || $value[0]=='#') continue;
if (eregi("\;$",$value)) {
$query .= $value;
if (eregi("^CREATE",$query)) {
$extra = substr(strrchr($query,')'),1);
$tabtype = substr(strchr($extra,'='),1);
$tabtype = substr($tabtype, 0, strpos($tabtype,strpos($tabtype,' ') ? ' ' : ';'));
$query = str_replace($extra,'',$query);
if (version_compare(mysql_get_server_info(), '4.1.0', '>=')) {
$extra = $dbcharset ? "ENGINE=$tabtype DEFAULT CHARSET=".$dbcharset.";" : "ENGINE=$tabtype;";
} else {
$extra = "TYPE=$tabtype;";
}
$query .= $extra;
} elseif(eregi("^INSERT",$query)) {
$query = 'REPLACE '.substr($query,6);
}
$this -> db -> query($query);
$query='';
} else{
$query.=$value;
}
}
}
public function getcreatFile($tb_arr,$sizelimit){
$path = '../data/db_backup';
if(!file_exists($path)){
$this->createDir($path);
}
$this->create_file($this->bakupTable($tb_arr).$this->bakupData($tb_arr,0,$sizelimit),'../data/db_backup/takoo_'.md5(date('Ymd_His')).'.sql');
}
/**读取文件**/
public function getBackupFileInfo() {
$filedb = array();
$handle = opendir('../data/db_backup');
while ($file = readdir($handle)) {
if (eregi("^takoo_",$file) && eregi("\.sql$",$file)) {
$strlen = eregi("^takoo_",$file) ? 16 + strlen("takoo_") : 19;
$fp = fopen("../data/db_backup/$file",'rb');
$bakinfo = fread($fp,filesize("../data/db_backup/$file"));
fclose($fp);
$detail=explode("\n",$bakinfo);
$bk['name'] = $file;
$bk['num'] = substr($detail[4],1);
$bk['version'] = substr($detail[2],1);
$bk['time'] = substr($detail[3],1);
$bk['pre'] = substr($file,0,$strlen);
$filedb[] = $bk;
}
}
return $this -> setFileInfo($filedb);
}
/**设计文件**/
private function setFileInfo($arr) {
$tmp1 = $tmp2 = array();
foreach ($arr as $k => $v) {
$tmp1[] = $v['pre'];
}
$dbf = array_unique($tmp1);
sort($dbf);
for($i=0,$max=intval(count($dbf));$i<$max;$i++) {
$j = 0;
foreach ($arr as $a => $b) {
if ($j == 0) {
$tmp2[$i]['name'] = $dbf[$i].'.sql';//$b['name']
$tmp2[$i]['num'] = $b['num'];
$tmp2[$i]['version'] = $b['version'];
$tmp2[$i]['time'] = $b['time'];
$tmp2[$i]['pre'] = $b['name'];
}
if ($b['pre'] == $dbf[$i]) {
$j += 1;
}
}
}
return $tmp2;
}
/**删除文件**/
public function delBackup($arr) {
if (!is_array($arr)) {
$file = '../data/db_backup/'.$d['name'];
self::delSqlFile($arr);
return true;
}
$farr = $this -> getBackupFileInfo();
foreach ($arr as $k => $v) {
self::delSqlFile($v);
}
}
private function delSqlFile($file) {
if (!is_file("../data/db_backup/".$file)) {
return false;
}
@chmod("../data/db_backup/".$file, 0777);
return @unlink("../data/db_backup/".$file);
}
public function __destruct() {
$this -> db = null;
}
private function createDir($dir) {
$flag = true;
$dir = str_replace(array('//','\\','\\\\'),'/',$dir);
if (!is_dir($dir))
{
$temp = explode('/',$dir);
$cur_dir = '';
for($i=0;$i<count($temp);$i++)
{
$cur_dir .= $temp[$i].'/';
if ([email protected]_dir($cur_dir))
{
if([email protected]($cur_dir,0777))
$flag = false;
}
$flag !== false and @chmod($cur_dir,0777);
}
}
return $flag;
}
public function create_file($data,$file,$cover="wb",$return = true){//ab追加 WB 覆盖
$file = str_replace("\\",'/',$file);
$p = dirname($file);
$p = substr($p,-1,1)!='/'?$p.'/':$p;
@$this->mkdirs($p);
$fp=fopen($file, $cover);
fwrite($fp,$data);//="\xEF\xBB\xBF".$text;
@flock($fp,2);
@fclose($fp);
@chmod($file, 0777);
if(!file_exists($file))return FALSE;
return $return?(filesize($file)?$file:0):FALSE;
}
private function mkdirs($path, $mode = 0777){
$path = str_replace("\\",'/',$path);
$dirs = explode('/',($path=substr($path,-1,1)!='/'?$path.'/':$path));
$pos = strrpos($path, ".");
$subamount = $pos === false?0:1;
for ($c=0;$c < count($dirs) - $subamount; $c++) {
$thispath="";
for ($cc=0; $cc <= $c; $cc++) {
$thispath.=$dirs[$cc].'/';
}
if (!file_exists($thispath))@mkdir($thispath,$mode);
}
}
}
?>
上一篇: Linux下MySQL主从复制(二)
下一篇: iOS判断两个时间戳是否同一天