备份:表结构和数据完全分开,默认有一个文件会记录所有表的结构,然后表中数据的备份 如果超过分卷的大小则会分成多个文件,不然则一个文件,参考了别人的代码,不过写的嘛,差强 人意,以后慢慢改吧。。。
代码如下:
<?php<BR>/*<BR> * Created on 2014<BR> * Link for [email protected]<BR> * This is seocheck backup class<BR> */<BR>class DbBackUp {<BR> private $conn;<BR> private $dbName;<BR> private $host;<BR> private $tag = '_b';<BR> //构造方法 链接数据库<BR> public function __construct($host='localhost', $dbUser='root', $dbPwd='', $dbName="seocheck", $charset='utf8') {<BR> @ob_start();<BR> @set_time_limit(0);<BR> $this->conn = mysql_connect($host, $dbUser, $dbPwd, true);<BR> if(!$this->conn) die("数据库系统连接失败!");<BR> mysql_query("set names ".$charset, $this->conn);<BR> mysql_select_db($dbName, $this->conn) or die("数据库连接失败!");<BR> $this->host = $host;<BR> $this->dbName = $dbName;<BR> }</P><P> //获取数据库所有表名<BR> public function getTableNames () {<BR> $tables = array();<BR> $result = mysql_list_tables($this->dbName, $this->conn);<BR> if(!$result) die('MySQL Error: ' . mysql_error());<BR> while($row = mysql_fetch_row($result)) {<BR> $tables[] = $row[0];<BR> }<BR> return $tables;<BR> }</P><P> //获取数据库表的字段信息<BR> public function getFieldsByTable ($table) {<BR> $fields = array();<BR> $str = '';<BR> $res = mysql_query("SHOW CREATE TABLE `{$table}`", $this->conn);<BR> if(!$res) die('MySQL Error: ' . mysql_error());<BR> while($rows = mysql_fetch_assoc($res)) {<BR> $str = str_replace("CREATE TABLE `{$table}` (", "", $rows['Create Table']);//DROP TABLE IF EXISTS `{$table}`\n<BR> $str = "--\n-- Table structure for table `{$table}`\n--\n\nCREATE TABLE IF NOT EXISTS `{$table}` ( ".$str;<BR> $str = str_replace(",", ", ", $str);<BR> $str = str_replace("`) ) ENGINE=InnoDB ", "`)\n ) ENGINE=InnoDB ", $str);<BR> $str .=";\n\n";<BR> //$str = $str.";\n\n--\n-- Dumping data for table `{$table}`\n--\n\n";<BR> $fields[$rows['Table']] = $str;<BR> }<BR> return $fields;<BR> }</P><P> //获取表中的数据<BR> public function getDataByTable($table) {<BR> $data = array();<BR> $str = '';<BR> $res = mysql_query("SELECT * FROM `{$table}`", $this->conn);<BR> if(!$res) die('MySQL Error: ' . mysql_error());<BR> while($rows = mysql_fetch_assoc($res)) {<BR> if(!empty($rows)) {<BR> $data[] = $rows;<BR> }<BR> }<BR> $keys = array_keys($data[0]);<BR> foreach ($keys as $k=>$v) {<BR> $keys[$k] = '`'.$v.'`';<BR> }<BR> $key = join(', ', $keys);<BR> $str = "INSERT INTO `{$table}` ({$key}) VALUES\n";<BR> foreach ($data as $k=>$v) {<BR> $str.="(";<BR> while (list($key, $val) = each($v)) {<BR> if(!is_numeric($val)) {<BR> $str.= "'".$val."', ";<BR> } else {<BR> $str.= $val.', ';<BR> }<BR> }<BR> $str = substr($str, 0, -2);// 后边有空格 所以从-2 开始截取<BR> if($k+1 == count($data)) {<BR> $str.=");\n\n-- --------------------------------------------------------\n\n";<BR> } else {<BR> $str.="),\n";<BR> }<BR> }<BR> return $str;<BR> }</P><P> //备份数据库<BR> public function getBackUpDataByTable ($tables, $path='', $fileName = 'seocheck', $subsection = '2') {<BR> if(empty($tables)) $this->_showMsg('未能指定要备份的表!!!', true);<BR> $page = 0;//卷数<BR> $path = empty($path) ? $_SERVER['DOCUMENT_ROOT'].'/core/Runtime/Data/'.$fileName.'Demo/' : $path;<BR> if(!file_exists($path)) {<BR> mkdir($path, 0777, true);<BR> }<BR> $mysql_info = $this->_retrieve();<BR> $fieldsByTable = array();<BR> if(is_array($tables)) {<BR> $this->_showMsg('开始备份,数据正在初始化中,请勿关闭浏览器...');<BR> $fw = $this->writeFileByBackUpData($path.$this->dbName.'_table.sql', $mysql_info, $method="ab+");<BR> if($fw !== false) {<BR> $this->_showMsg('备份数据库基本信息成功。。。');<BR> }<BR> foreach ($tables as $table) {<BR> $tableInfo = $this->getFieldsByTable($table);<BR> if(!empty($tableInfo)) {<BR> $this->_showMsg('获取表['.$table.']结构成功。。。');<BR> $fw = $this->writeFileByBackUpData($path.$this->dbName.'_table.sql', $tableInfo[$table], $method="ab+");<BR> if($fw === false) {<BR> $this->_showMsg('备份表['.$table.']结构失败。。。', true);<BR> } else {<BR> $this->_showMsg('备份表['.$table.']结构成功,开始获取数据。。。');<BR> };<BR> } else {<BR> $this->_showMsg('获取数据库['.$this->dbName.']表结构失败,请稍后再试!。。。', true);<BR> }<BR> $this->_insertSqlByTableForAll($path, $table, $subsection);<BR> }<BR> } else {<BR> $this->_showMsg('开始备份,数据正在初始化中,请勿关闭浏览器...');<BR> $tableInfo = $this->getFieldsByTable($tables);<BR> if(!empty($tableInfo)) {<BR> $this->_showMsg('获取表['.$tables.']结构成功。。。');<BR> $fw = $this->writeFileByBackUpData($path.$this->dbName.'_'.$tables.'_table.sql', $mysql_info.$tableInfo[$tables]);<BR> if($fw === false) {<BR> $this->_showMsg('备份表['.$tables.']结构失败。。。', true);<BR> } else {<BR> $this->_showMsg('备份表['.$tables.']结构成功,开始获取数据。。。');<BR> }<BR> } else {<BR> $this->_showMsg('获取表['.$tables.']结构失败,请稍后再试!。。。', true);<BR> }<BR> $res = $this->_insertSqlByTableForAll($path, $tables, $subsection);<BR> }<BR> }</P><P> //数据库基本信息<BR> private function _retrieve() {<BR> $backUp = '';<BR> $backUp .= '--' . "\n";<BR> $backUp .= '-- MySQL database dump' . "\n";<BR> $backUp .= '-- Created by DbBackUp class, Power By chujiu. ' . "\n";<BR> $backUp .= '--' . "\n";<BR> $backUp .= '-- 主机: ' . $this->host . "\n";<BR> $backUp .= '-- 生成日期: ' . date ( 'Y' ) . ' 年 ' . date ( 'm' ) . ' 月 ' . date ( 'd' ) . ' 日 ' . date ( 'H:i' ) . "\n";<BR> $backUp .= '-- MySQL版本: ' . mysql_get_server_info () . "\n";<BR> $backUp .= '-- PHP 版本: ' . phpversion () . "\n";<BR> $backUp .= "\n\n";<BR> $backUp .= "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO';\n";<BR> $backUp .= "SET time_zone = '+00:00';\n\n";<BR> $backUp .= "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n";<BR> $backUp .= "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n";<BR> $backUp .= "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n";<BR> $backUp .= "/*!40101 SET NAMES utf8*/;\n\n";<BR> $backUp .= "--\n-- Database: `{$this->dbName}`\n--\n\n-- --------------------------------------------------------\n\n";<BR> return $backUp;<BR> }</P><P> /**<BR> * 插入单条记录<BR> *<BR> * @param string $row<BR> */<BR> private function _insertSql($row, $table) {<BR> // sql字段逗号分割<BR> $insert = '';<BR> $insert .= "INSERT INTO `" . $table . "` VALUES(";<BR> foreach($row as $key=>$val) {<BR> $insert .= "'".$val."',";<BR> }<BR> $insert = substr($insert, 0 ,-1);<BR> $insert .= ");" . "\n";<BR> return $insert;<BR> }</P><P> /**<BR> * 生成一个表的inser语句<BR> * @param string $table<BR> * @param string $subsection 分卷大小<BR> */<BR> private function _insertSqlByTableForAll($path, $table, $subsection) {<BR> $i = 0;<BR> $insertSqlByTable = '';<BR> $res = mysql_query("SELECT * FROM `{$table}`", $this->conn);<BR> if(!$res) die('MySQL Error: ' . mysql_error());<BR> while($rows = mysql_fetch_assoc($res)) {<BR> $insertSqlByTable .= $this->_insertSql($rows, $table);<BR> $size = strlen($insertSqlByTable);<BR> if($size > $subsection*1024*1024) {<BR> $fw = $this->writeFileByBackUpData($path.$table.$i.$this->tag.'.sql', $insertSqlByTable);<BR> if($fw === false) $this->_showMsg('数据库表['.$table.'],卷 '.$i.' 写入文件失败,请稍后再试!!!',true);<BR> $this->_showMsg('数据库表['.$table.'],卷 '.$i.' 备份成功!备份文件:[ '.$path.$table.$i.$this->tag.'.sql ]');<BR> $insertSqlByTable = '';<BR> $i+=1;<BR> }<BR> }<BR> // insertSqlByTable大小不够分卷大小<BR> if ($insertSqlByTable != "") {<BR> $fw = $this->writeFileByBackUpData($path.$table.$this->tag.'.sql', $insertSqlByTable);<BR> if($fw === false) $this->_showMsg('数据库表['.$table.']写入文件失败,请稍后再试!!!备份文件:[ '.$path.$table.$this->tag.'.sql ]',true);<BR> $this->_showMsg('数据库表['.$table.'] 备份成功!备份文件:[ '.$path.$table.$this->tag.'.sql ]');<BR> }<BR> $this->_showMsg('数据库表['.$table.']全部备份成功!');<BR> }</P><P> // 写入文件<BR> public function writeFileByBackUpData($fileName, $data, $method="rb+", $iflock=1, $check=1, $chmod=1){<BR> $check && @strpos($fileName, '..')!==false && exit('Forbidden');<BR> @touch($fileName);<BR> $handle = @fopen($fileName, $method);<BR> if($iflock) {<BR> @flock($handle,LOCK_EX);<BR> }<BR> $fw = @fwrite($handle,$data);<BR> if($method == "rb+") ftruncate($handle, strlen($data));<BR> fclose($handle);<BR> $chmod && @chm<div>本文来*源gaodai^.ma#com搞#代!码网</div><pre>搞gaodaima代码
od($fileName,0777);
return $fw;
}
/**
* path: 生成压缩包的路径
* fileName : 要压缩的文件名 通常和path 同一目录
*/
public function createZipByBackUpFile($path) {
$db_base_files = $this->getFileByBackUpDir($path);
if(!empty($db_base_files)) {
$zip = new ZipArchive;
if($zip->open($path.$this->dbName.date(‘Ymd’).’.zip’, ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
die (“cannot open”.$this->dbName.date(‘Ymd’).”zip for writing.”);
foreach ($db_base_files as $key => $value) {
if(is_file($value)) {
$file_name = basename($value);
$info[] = $zip->addFile($value, $file_name);// 避免压缩包里有文件的路径
}
}
$zip->close();
if(file_exists($path.$this->dbName.date(‘Ymd’).’.zip’))
foreach ($db_base_files as $val) {
unlink($val);
}
if(count(array_filter($info)) > 0) return true;
}
return false;
}
//获取文件
public function getFileByBackUpDir($path) {
$info = array();
$db_base_files = array();
if( @file_exists($path) && is_dir($path) ) {
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
if($file != ‘.’ && $file != ‘..’) {
if( strripos($file, ‘seocheck’) !== false ) {
$db_base_files[] = $path.$file;
}
}
}
closedir($dh);
}
}
return $db_base_files;
}
/**
* @path: 生成压缩包的路径
* @fileName : 要解压的文件名 默认解压到path 目录
*/
public function uncompressZip($path, $zipName) {
$path = empty($path) ? $_SERVER[‘DOCUMENT_ROOT’].’/core/Runtime/Data/’ : $path;
$zip = new ZipArchive;
if ($zip->open($path.$zipName) === TRUE) {
$zip->extractTo($path);
$zip->close();
return true;
} else {
return false;
}
}
//导入数据库
public function importingDataBySqlFile () {
}
// 及时输出信息
private function _showMsg($msg,$err=false){
if($err === true) {
echo “
ERROR: — ” . $msg . “
“;exit;
}
echo “
OK: — ” . $msg . “
“;
}
// 锁定数据库,以免备份或导入时出错
private function lock($table, $op = “WRITE”) {
if (mysql_query ( “lock tables ” . $table . ” ” . $op ))
return true;
else
return false;
}
// 解锁
private function unlock() {
if (mysql_query ( “unlock tables” ))
return true;
else
return false;
}
// 析构
public function __destruct() {
if($this->conn){
mysql_query ( “unlock tables”, $this->conn );
mysql_close ( $this->conn );
}
}
}
?>