PHP備份MYSQL數據庫

<?php
require(dirname(__FILE__).'/config.php');

//備份
if(post_get('act', 1)=='bak'){
	$file_name = $_POST['file'];
	
	$bak_connection = db::factory('mysql');
	$query  = 'show tables';
	$tables_arr = $bak_connection->get_array($query);
	$file_content = '';
	//遍歷所有表
	foreach($tables_arr as $value){
		$table = $value['Tables_in_'.$current_conf['DBNAME']];
		if(!empty($table)){
			$query = 'show create table '.$table;
			$file_content  .= "DROP TABLE IF EXISTS `$table`;\r\n";
			//表結構
			$table_destruct = $bak_connection->get_array($query);
			$file_content  .= str_replace("\n", '', str_replace("\r\n", "\n", $table_destruct[0]['Create Table'])) . ";\r\n\r\n";
			//$msg = $table.'表結構備份完畢';
			//表數據
			$query = 'SELECT * FROM '.$table;
			$table_data = $bak_connection->get_array($query);
			foreach($table_data as $key => $value){
				$file_content .= "INSERT INTO `$table` VALUES('";
				$value_arr     = array_values($value);
				$file_content .= implode("','" , $value_arr);
				$file_content .= "');\r\n\r\n";
			}
			//$msg .= $table.'表數據備份完畢';
		}
	}
	
	$file_content = iconv('GBK' , 'UTF-8' , $file_content);
	/*
	$fp = fopen($path , 'w') or die('文件不可寫,或不存在');
	fputs($fp , $file_content);
	fclose($fp);
	unset($fp);
	*/
	header("Content-type: text/plain");
    header("Accept-Ranges: bytes");
    header("Content-Disposition: attachment; filename=".$file_name);
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0" );
    header("Pragma: no-cache" );
    header("Expires: 0" ); 
    exit($file_content);
	
}
//還原
if(post_get('act', 1)=='restore'){
	$sql_file = $_POST['file'];
	
	$bak_connection = db::factory('mysql');
	$fp = fopen($sql_file , 'r');
	while(!feof($fp)){
		$line = fgets($fp);
		if(trim($line)!='' || trim($line)!=null){
			$temp_line = iconv('utf-8' , 'gbk' , $line);
			$result = $bak_connection->execute($temp_line);
			if($result){
				redirect('back.php' , '還原成功');
			}
			redirect('back.php' , '還原失敗');
		}
	}
	
}


config.php這個文件是我自己的,主要是用來提供生成MYSQL連接的。

$bak_connection = db::factory('mysql');

不知道的可以參考我以前寫的http://blog.csdn.net/tomyjohn/article/details/7675770

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章