php mysql数据库备份类

本文章主要是介绍关于用php对mysql数据库,与数据表以及数据进行备份了,代码写得有一点长不过行行都是实例了,好了费话不说多了我们来看看这款mysql数据库备份代码的吧。

这个程序仅仅备份和恢复数据,使用方法很简单,实例化DbBak,然后调用bakupDb和restoreDb方法:
   1、实例化DbBak需要告诉它两件事:数据服务器在哪里($connectid)、备份到哪个目录($backupDir):

require_once('DbBak.php');
<?php
//只有DbBak才能调用这个类
class TableBak{
        var $_mysql_link_id;
        var $_dbDir;
        //private $_DbManager;
        function TableBak($mysql_link_id,$dbDir)
        {
                $this->_mysql_link_id = $mysql_link_id;
                $this->_dbDir = $dbDir;
        }
       
        function backupTable($tableName)
        {
                //step1:创建表的备份目录名:
                $tableDir = $this->_dbDir.DIRECTORY_SEPARATOR.$tableName;
                !is_dir($tableDir) && mkdir($tableDir);
                //step2:开始备份:
                $this->_backupTable($tableName,$tableDir);
        }
       
        function restoreTable($tableName,$tableBakFile)
        {
                set_time_limit(0);
                $fileArray = @file($tableBakFile) or die("can open file $tableBakFile");
                $num = count($fileArray);
                mysql_unbuffered_query("DELETE FROM $tableName");
                $sql = $fileArray[0];
                for ($i=1;$i<$num-1;$i++){                       
                        mysql_unbuffered_query($sql.$fileArray[$i]) or (die (mysql_error()));
                }
                return true;
        }
       
        function _getFieldInfo($tableName){
                $fieldInfo = array();
                $sql="SELECT * FROM $tableName LIMIT 1";
                $result = mysql_query($sql,$this->_mysql_link_id);
                $num_field=mysql_num_fields($result);
                for($i=0;$i<$num_field;$i++){
                        $field_name=mysql_field_name($result,$i);
                        $field_type=mysql_field_type($result,$i);
                        $fieldInfo[$field_name] = $field_type;
                }
                mysql_free_result($result);
                return $fieldInfo;
        }
        function _quoteRow($fieldInfo,$row){
                foreach ($row as $field_name=>$field_value){
                        $field_value=strval($field_value);
                        switch($fieldInfo[$field_name]){ 
                                case "blob":     $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;                         
                                case "string":   $row[$field_name] = "'".mysql_escape_string($field_value)."'";break; 
                                case "date":          $row[$field_name] = "'".mysql_escape_string($field_value)."'";break; 
                                case "datetime": $row[$field_name] = "'".mysql_escape_string($field_value)."'";break; 
                                case "time":          $row[$field_name] = "'".mysql_escape_string($field_value)."'";break; 
                                case "unknown":  $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;                                         
                                case "int":          $row[$field_name] = intval($field_value); break;
                                case "real":     $row[$field_name] = intval($field_value); break;
                                case "timestamp":$row[$field_name] = intval($field_value); break;
                                default:                  $row[$field_name] = intval($field_value); break;
                        }
                }
                return $row;
        }
        function _backupTable($tableName,$tableDir)
        {
                //取得表的字段类型:
                $fieldInfo = $this->_getFieldInfo($tableName);
               
                //step1:构造INSERT语句前半部分 并写入文件:
                $fields = array_keys($fieldInfo);
                $fields = implode(',',$fields);
                $sqltext="INSERT INTO $tableName($fields)VALUES rn";
                $datafile = $tableDir.DIRECTORY_SEPARATOR.$tableName.'.sql';
                (!$handle = fopen($datafile,'w')) && die("can not open file <b>$datafile</b>");
                (!fwrite($handle, $sqltext))  && die("can not write data to file <b>$datafile</b>");
                fclose($handle);
               
                //step2:取得数据 并写入文件:
                //取出表资源:
                set_time_limit(0);
                $sql = "select * from $tableName";
                $result = mysql_query($sql,$this->_mysql_link_id);
                //打开数据备份文件:$tableName.xml
                $datafile = $tableDir.DIRECTORY_SEPARATOR.$tableName.'.sql';
                (!$handle = fopen($datafile,'a')) && die("can not open file <b>$datafile</b>");
                //逐条取得表记录并写入文件:
                while ($row = mysql_fetch_assoc($result)) {
                        $row = $this->_quoteRow($fieldInfo,$row);       
                        $record='(' . implode(',',$row) . ");rn";
                        (!fwrite($handle, $record))  && die("can not write data to file <b>$datafile</b>");
                }
                mysql_free_result($result);
                //关闭文件:
                fclose($handle);
               
                return true;
        }

}
?>
require_once('TableBak.php');
这个文件代码

require_once('TableBak.php');
class DbBak {
        var $_mysql_link_id;
        var $_dataDir;
        var $_tableList;
        var $_TableBak;
       
        function DbBak($_mysql_link_id,$dataDir)
        {
                ( (!is_string($dataDir)) || strlen($dataDir)==0) && die('error:$datadir is not a string');
                !is_dir($dataDir) && mkdir($dataDir);
                $this->_dataDir = $dataDir;
                $this->_mysql_link_id = $_mysql_link_id;
        }
       
        function backupDb($dbName,$tableName=null)
        {
                ( (!is_string($dbName)) || strlen($dbName)==0 ) && die('$dbName must be a string value');
                //step1:选择数据库:
                mysql_select_db($dbName);
                //step2:创建数据库备份目录
                $dbDir = $this->_dataDir.DIRECTORY_SEPARATOR.$dbName;
                !is_dir($dbDir) && mkdir($dbDir);
                //step3:得到数据库所有表名 并开始备份表
                $this->_TableBak = new TableBak($this->_mysql_link_id,$dbDir);
                if(is_null($tableName)){//backup all table in the db
                        $this->_backupAllTable($dbName);
                        return;
                }
                if(is_string($tableName)){
                        (strlen($tableName)==0) && die('....');
                        $this->_backupOneTable($dbName,$tableName);
                        return;
                }
                if (is_array($tableName)){
                        foreach ($tableName as $table){
                                ( (!is_string($table)) || strlen($table)==0 ) && die('....');
                        }
                        $this->_backupSomeTalbe($dbName,$tableName);
                        return;
                }
        }
       
        function restoreDb($dbName,$tableName=null){
                ( (!is_string($dbName)) || strlen($dbName)==0 ) && die('$dbName must be a string value');
                //step1:检查是否存在数据库 并连接:
                @mysql_select_db($dbName) || die("the database <b>$dbName</b> dose not exists");
                //step2:检查是否存在数据库备份目录
                $dbDir = $this->_dataDir.DIRECTORY_SEPARATOR.$dbName;
                !is_dir($dbDir) && die("$dbDir not exists");
                //step3:start restore
                $this->_TableBak = new TableBak($this->_mysql_link_id,$dbDir);
                if(is_null($tableName)){//backup all table in the db
                        $this->_restoreAllTable($dbName);
                        return;
                }
                if(is_string($tableName)){
                        (strlen($tableName)==0) && die('....');
                        $this->_restoreOneTable($dbName,$tableName);
                        return;
                }
                if (is_array($tableName)){
                        foreach ($tableName as $table){
                                ( (!is_string($table)) || strlen($table)==0 ) && die('....');
                        }
                        $this->_restoreSomeTalbe($dbName,$tableName);
                        return;
                }
        }
       
        function _getTableList($dbName)
        {
                $tableList = array();
                $result=mysql_list_tables($dbName,$this->_mysql_link_id);
                for ($i = 0; $i < mysql_num_rows($result); $i++){
                array_push($tableList,mysql_tablename($result, $i));
                }
                mysql_free_result($result);
                return $tableList;
        }
       
        function _backupAllTable($dbName)
        {
                foreach ($this->_getTableList($dbName) as $tableName){
                        $this->_TableBak->backupTable($tableName);
                }
        }
       
        function _backupOneTable($dbName,$tableName)
        {
                !in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名<b>$tableName</b>在数据库中不存在");
                $this->_TableBak->backupTable($tableName);
        }
       
        function _backupSomeTalbe($dbName,$TableNameList)
        {
                foreach ($TableNameList as $tableName){
                        !in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名<b>$tableName</b>在数据库中不存在");
                }
                foreach ($TableNameList as $tableName){
                        $this->_TableBak->backupTable($tableName);
                }
        }
       
        function _restoreAllTable($dbName)
        {
                //step1:检查是否存在所有数据表的备份文件 以及是否可写:
                foreach ($this->_getTableList($dbName) as $tableName){
                        $tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR
                                                       . $dbName.DIRECTORY_SEPARATOR
                                                      . $tableName.DIRECTORY_SEPARATOR
                                               . $tableName.'.sql';
                        !is_writeable ($tableBakFile) && die("$tableBakFile not exists or unwirteable");
                }
                //step2:start restore
                foreach ($this->_getTableList($dbName) as $tableName){
                        $tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR
                                                      . $dbName.DIRECTORY_SEPARATOR
                                                      . $tableName.DIRECTORY_SEPARATOR
                                                      . $tableName.'.sql';
                        $this->_TableBak->restoreTable($tableName,$tableBakFile);
                }
        }
       
        function _restoreOneTable($dbName,$tableName)
        {
                //step1:检查是否存在数据表:
                !in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名<b>$tableName</b>在数据库中不存在");
                //step2:检查是否存在数据表备份文件 以及是否可写:
                $tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR
                                            . $dbName.DIRECTORY_SEPARATOR
                                             . $tableName.DIRECTORY_SEPARATOR
                                            . $tableName.'.sql';
                !is_writeable ($tableBakFile) && die("$tableBakFile not exists or unwirteable");
                //step3:start restore
                $this->_TableBak->restoreTable($tableName,$tableBakFile);
        }
        function _restoreSomeTalbe($dbName,$TableNameList)
        {
                //step1:检查是否存在数据表:
                foreach ($TableNameList as $tableName){
                        !in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名<b>$tableName</b>在数据库中不存在");
                }
                //step2:检查是否存在数据表备份文件 以及是否可写:
                foreach ($TableNameList as $tableName){
                        $tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR
                                                      . $dbName.DIRECTORY_SEPARATOR
                                                      . $tableName.DIRECTORY_SEPARATOR
                                                      . $tableName.'.sql';
                        !is_writeable ($tableBakFile) && die("$tableBakFile not exists or unwirteable");
                }
                //step3:start restore:
                foreach ($TableNameList as $tableName){
                        $tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR
                                                      . $dbName.DIRECTORY_SEPARATOR
                                                      . $tableName.DIRECTORY_SEPARATOR
                                                      . $tableName.'.sql';
                        $this->_TableBak->restoreTable($tableName,$tableBakFile);
                }
        }
}
?>

$connectid = mysql_connect('localhost','root','123456');

$backupDir = 'data';

$DbBak = new DbBak($connectid,$backupDir);
复制代码2、然后就可以开始备份数据库了,你不仅能够指定备份那个数据库,而且能详细设置只备份那几个表:
  2.1如果你想备份mybbs库中的所有表,只要这样: $DbBak->backupDb('mybbs');
复制代码2.2如果你只想备份mybbs库中的board、face、friendlist表,可以用一个一维数组指定: $DbBak->backupDb('mybbs',array('board','face','friendsite'));
复制代码2.3如果只想备份一个表,比如board表: $DbBak->backupDb('mybbs','board');
复制代码3,数据恢复:
对于2.1、2.1、2.3三种情况,只要相应的修改下语句,把backupDb换成restoreDb就能实现数据恢复了: $DbBak->restoreDb('mybbs');
复制代码$DbBak->restoreDb('mybbs',array('board','face','friendsite'));
复制代码$DbBak->restoreDb('mybbs','board');

测试实例

//example 1 backup:
require_once('DbBak.php');
require_once('TableBak.php');
$connectid = mysql_connect('localhost','root','123456');
$backupDir = 'data';
$DbBak = new DbBak($connectid,$backupDir);
$DbBak->backupDb('mybbs');

require_once('DbBak.php');
require_once('TableBak.php');
$connectid = mysql_connect('localhost','root','123456');
$backupDir = 'data';
$DbBak = new DbBak($connectid,$backupDir);
$DbBak->restoreDb('mybbs');

时间: 2024-09-13 17:27:29

php mysql数据库备份类的相关文章

PHP Mysql数据库备份类程序总结

数据库备份类 使用方法:  代码如下 复制代码   require_once("backdata.class.php"); $link = @mysql_connect("localhost","数据库名","密码") or die ('Could not connect to server.'); mysql_query("use cms",$link); mysql_query("set na

php实现mysql数据库备份类_php实例

1.实例化DbBak需要告诉它两件事:数据服务器在哪里($connectid).备份到哪个目录($backupDir):  require_once('DbBak.php');     require_once('TableBak.php');     $connectid = mysql_connect('localhost','root','123456');     $backupDir = 'data';     $DbBak = new DbBak($connectid,$backup

mysql数据库备份类

<?php教程 $cfg_dbhost ='localhost';//mysql教程主机 $cfg_dbname ='sq_test';//数据库教程名 $cfg_dbuser ='root';//数据库用户名 $cfg_dbpwd ='111cn.net';//数据库用户密码 $cfg_db_language ='utf8';//数据库编码 class dbmysql{ public static $dbhost = 'localhost'; public static $dbname; pu

php实现MySQL数据库备份与还原类实例_php技巧

本文实例讲述了php实现MySQL数据库备份与还原类.分享给大家供大家参考.具体分析如下: 这是一个非常简单的利用php来备份mysql数据库的类文件,我们只要简单的在dbmange中配置好连接地址用户名与数据库即可,下面我们一起来看这个例子,代码如下: 复制代码 代码如下: <?php   /**   * 创建时间: 2012年5月21日   *   * 说明:分卷文件是以_v1.sql为结尾(20120522021241_all_v1.sql)   * 功能:实现mysql数据库分卷备份,选

mysql 数据库备份和还原方法集锦 推荐_Mysql

作/译者:叶金荣(Email: ),来源:http://imysql.cn/,转载请注明作/译者和出处,并且不能用于商业用途,违者必究. 日期:2006/10/01 本文讨论 MySQL 的备份和恢复机制,以及如何维护数据表,包括最主要的两种表类型:MyISAM 和 Innodb,文中设计的 MySQL 版本为 5.0.22. 目前 MySQL 支持的免费备份工具有:mysqldump.mysqlhotcopy,还可以用 SQL 语法进行备份:BACKUP TABLE 或者 SELECT INT

二款php数据库备份类程序代码

下面看下使用方法:  代码如下 复制代码 <?php error_reporting(0);//消灭万恶的php报警提示 //设定邮箱 $options = array('email' => array('email1', 'email2'), 'folder' => './backup/', 'mysql' => array('localhost', 'user', 'password', 'db'));   $b = new Backup($options);     // 提

Mysql数据库备份和还原常用的命令

Mysql数据库备份和还原常用的命令是进行Mysql数据库备份和还原的关键,没有命令,什么都无从做起,更谈不上什么备份还原,只有给系统这个命令,让它去执行,才能完成Mysql数据库备份和还原的操作,下面就是操作的常用命令. 一.备份命令 1.备份MySQL数据库的命令 mysqldump-hhostname-uusername-ppassword databasename>backupfile.sql 2.备份MySQL数据库为带删除表的格式 备份MySQL数据库为带删除表的格式,能够让该备份覆

MySQL 数据库备份恢复和乱码问题 续

在我转到wordpress之后第一个考虑的是它的数据库备份恢复问题,因为写bloger都知道,自己的blog记录的都是自己需要的宝贵的资料和文字,如果因为各种未知因素导致数据库崩溃或者空间商出了问题,丢失了数据的话,无疑是一种非常巨大的痛苦和损失. 所以在我blog里面有好几篇资料文章或者自己心得文章来讨论mysql数据库备份恢复和乱码问题. 之前那些文章讨论结果已经暂时能满足我数据库备份和恢复问题了,但是始终有个让我不能完全安心的地方,那就是用PMA恢复的时候,使用的是上传机制,那么PHP默认

MySQL数据库备份(转)

mysql|备份|数据|数据库 MySQL数据库备份[晏子]  http://clyan.hongnet.com/index.html在数据库表丢失或损坏的情况下,备份你的数据库是很重要的.如果发生系统崩溃,你肯定想能够将你的表尽可能丢失最少的数据恢复到崩溃发生时的状态.有时,正是MySQL管理员造成破坏.管理员已经知道表以破坏,用诸如vi或Emacs等编辑器试图直接编辑它们,这对表绝对不是件好事!备份数据库两个主要方法是用mysqldump程序或直接拷贝数据库文件(如用cp.cpio或tar等