WEB开发网
开发学院WEB开发PHP PHP备份MYSQL数据库 阅读

PHP备份MYSQL数据库

 2012-08-09 09:19:03 来源:WEB开发网   
核心提示:<?phprequire(dirname(__FILE__).'/config.php');//备份if(post_get('act', 1)=='bak'){$file_name = $_POST['file'];$bak_connection =
<?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');

Tags:PHP 备份 MYSQL

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接