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

你可能感兴趣的:(PHP备份MYSQL数据库)