1.   阿里云服务器1888元代金券领取
  2.   本网站所有源码包解压密码:www.youhutong.com
登录  帮助问答

PHP mysql数据库备份、数据库数据还原类(源码)

小川 技术文章
郑重声明:
  本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,否则后果请用户自负,下载后请24小时内删除。 本站所有内容均不能保证其完整性,不提供任何技术支持,不能接受请勿购买或下载,如需完整程序,请去其官方购买正版使用。
下载源码  
【温馨提示】源码包解压密码:www.youhutong.com

mysql数据库备份、数据库数据还原类


1、数据库备份使用说明:

    1):引入类库文件,然后实例化类

    2):最后调用备份方法,并传入相关参数

//------1. 数据库备份(导出)--------------------
require './DbManage.php';
#  分别是主机,用户名,密码,数据库名,数据库编码
$config = [
    'hostname'        => 'localhost',
    'database'        => 'test',
    'username'        => 'root',
    'password'        => 'root',
    'charset'         => 'utf8',
];
$db = new DBManage($config);
#  参数1[必选]:string 备份目录
#  参数2[可选]:string 备份哪个表(默认备份全部)
#  参数3[可选]:int    分卷大小  (默认不分卷)
$db->backup ('./backup/');



2、数据库导入使用说明:

    1):引入类库文件,然后实例化类

    2):最后调用导入方法,并传入相关参数

//------1. 数据库还原(导入)--------------------
require './DbManage.php';
#  分别是主机,用户名,密码,数据库名,数据库编码
$config = [
    'hostname'        => 'localhost',
    'database'        => 'test',
    'username'        => 'root',
    'password'        => 'root',
    'charset'         => 'utf8',
];
$db = new DBManage($config);
#  参数1[必选]:string  sql文件目录
#  参数3[可选]:boolean false单文件导入(默认)   true多文件导入
$db->import('./backup/20190628test_1.sql');


类源码:

<?php
// +----------------------------------------------------------------------
// | Title : Mysql数据库备份类
// +----------------------------------------------------------------------
// | Author: xiaochuan <28126649@qq.com>
// +----------------------------------------------------------------------
// | Blog  : www.youhutong.com
// +----------------------------------------------------------------------
// | Date  : 2019-05-30
// +----------------------------------------------------------------------
/*
    1. 数据库备份(导出)---------
    $config = [
        'hostname'        => 'localhost',
        'database'        => 'demo',
        'username'        => 'root',
        'password'        => 'root',
        'charset'         => 'utf8',
    ];
    $db = new DBManage($config);
    $db->backup('./backup/');

    2. 数据库恢复(导入)---------
    $config = [
        'hostname'        => 'localhost',
        'database'        => 'demo',
        'username'        => 'root',
        'password'        => 'root',
        'charset'         => 'utf8',
    ];
    $db = new DBManage($config);
    $db->backup('./backup/database.sql');
*/
class DbManage
{
    #  数据库链接
    private $db;
    #  当前数据库名
    private $database;
    #  分卷大小,默认无限止
    private $size = 0;
    #  备份目录
    private $path;
    #  待写入文件内容
    private $value = '';
    #  当前分卷
    private $page = 1;
    #  数据库配置数组
    private $config = [
        #  服务器地址
        'hostname'        => 'localhost',
        #  数据库名
        'database'        => 'test',
        #  用户名
        'username'        => 'root',
        #  密码
        'password'        => 'root',
        #  数据库编码
        'charset'         => 'utf8',
    ];
    /**
     * 构造方法
     * @param array $config 数据库配置数组
     */
    public function __construct(array $config=[])
    {
        date_default_timezone_set('PRC');
        set_time_limit(0);
        @ob_end_flush();
        #  处理配置数据
        if(!empty($config)){
            $this->config = array_merge($this->config, $config);
        }
        #  链接数据库
        $this->db = @mysqli_connect(
            $this->config['hostname'], 
            $this->config['username'], 
            $this->config['password'], 
            $this->config['database']
        );
        if(!$this->db){
            $this->showLog('链接数据库失败: '.mysqli_connect_error(), true);
        }
        #  数据库编码方式
        @mysqli_query($this->db, 'set names '.$this->config['charset']);
    }

    /**
     * 输出运行信息
     * @access private
     * @param string $msg   [可选]运行信息
     * @param boolean $type [可选]是否退出程序
     * @return string
     */
    private function showLog($msg='', $type=false)
    {
        $tpl = '<div style="color:red;">%s</div>';
        echo sprintf($tpl, $msg);
        flush();
        if($type) die;
    }

    /**
     * 写入数据库备份基础信息
     * @access private
     * @return string
     */
    private function addHeader()
    {
        $this->value  = '-- +------------------------------------------------------' . PHP_EOL;
        $this->value .= '-- | Title  : Mysql数据库备份文件' . PHP_EOL;
        $this->value .= '-- +------------------------------------------------------' . PHP_EOL;
        $this->value .= '-- | Author : xiaochuan <28126649@qq.com>' . PHP_EOL;
        $this->value .= '-- +------------------------------------------------------' . PHP_EOL;
        $this->value .= '-- | Blog   : www.youhutong.com' . PHP_EOL;
        $this->value .= '-- +------------------------------------------------------' . PHP_EOL;
        $this->value .= '-- | Date   : '. date('Y-m-d H:i:s') . PHP_EOL;
        $this->value .= '-- +------------------------------------------------------' . PHP_EOL;
        $this->value .= '-- | 主机     : ' . $this->config['hostname'] . PHP_EOL;
        $this->value .= '-- | Mysql版本: ' . mysqli_get_server_info($this->db) . PHP_EOL;
        $this->value .= '-- | PHP 版本 : ' . phpversion() . PHP_EOL;
        $this->value .= '-- | 数据库名 : ' . $this->config['database'] . PHP_EOL;
        $this->value .= '-- | 导出时间 : ' . date('Y-m-d H:i:s') . PHP_EOL;
        $this->value .= '-- +------------------------------------------------------' . PHP_EOL;
        $this->value .= PHP_EOL . PHP_EOL;
        return $this->value;
    }

    /**
     * 写入表结构
     * @access private
     * @param string $table 数据库表名
     * @return string
     */
    private function addTable($table)
    {
        #  获取创建表语句
        $obj = mysqli_query($this->db, 'show create table `' . $table . '`');
        $result = mysqli_fetch_array($obj);
        $this->value .= '-- ------------------------------------' . PHP_EOL;
        $this->value .= '-- ['. $table .']表结构和数据' . PHP_EOL;
        $this->value .= '-- ------------------------------------' . PHP_EOL;
        $this->value .= '-- 结构' . PHP_EOL;
        $this->value .= 'DROP TABLE IF EXISTS `' . $table . '`;'. PHP_EOL;
        $this->value .= $result[1] . ';' . PHP_EOL;
        return $this->value;
    }

    /**
     * 写入表数据
     * @access private
     * @param string $table 数据库表名
     * @return null
     */
    private function addData($table)
    {
        #  获取表中数据
        $obj = mysqli_query($this->db, 'SELECT * FROM ' . $table);
        #  判断如果没有数据
        $count = mysqli_num_rows($obj);
        if(!$count){
            $this->value .= '-- '.$table.'表无数据' . PHP_EOL . PHP_EOL . PHP_EOL;
            return;
        }else{
            $this->value .= '-- 数据' . PHP_EOL;
        }
        #  统计有多少个字段
        $count = mysqli_num_fields($obj);
        while($result = mysqli_fetch_array($obj)){
            $comma = '';
            $this->value .= 'INSERT INTO `' . $table . '` VALUES(';
            for($i=0; $i<$count; $i++){
                $str = mysqli_real_escape_string($this->db, $result[$i]);
                $this->value .= ($comma . '\'' . $str . '\'');
                $comma = ', ';
            }
            $this->value .= ");" . PHP_EOL;
            
            #  判断是否设置分卷大小 并 达到设置分卷大小
            if($this->size && strlen($this->value) >= $this->size){
                $ste = $this->saveFile();
                if($ste){
                    $msg = '正在进行备份第' .($this->page + 1). '卷......'. PHP_EOL;
                    $this->showLog($msg);
                    $this->addHeader();

                }else{
                    $msg = '备份失败,请重新备份'. PHP_EOL;
                    $this->showLog($msg, true);
                }
                $this->page = $this->page + 1;
            }
        }
        $this->value .= PHP_EOL . PHP_EOL;
        unset($obj, $result);
    }

    /**
     * 写入文件
     * @access private
     * @return null
     */
    private function saveFile()
    {
        $filename = date('Ymd') . $this->config['database'] . '_' . $this->page .'.sql';
        $ste = @file_put_contents($this->path .'/'. $filename, $this->value);
        if(!$ste) $this->showLog("写入sql文件失败!");
        #  写入正常
        $msg  = '第'. $this->page .'卷备份完成,地址:'. $this->path .'/'. $filename . PHP_EOL;
        $this->showLog($msg);
        return $ste;
    }

    /**
     * 数据库备份(主调用方法)
     * @access public
     * @param string $path  [必须]备份目录
     * @param string $table [可选]备份单表,默认全部
     * @param int $size     [可选]分卷大小, 默认不分卷
     * @return string
     */
    public function backup($path='', $table='', $size='')
    {
        $this->size = (int)$size;
        #  直接转成字节大小
        $this->size = $this->size * 1024 * 1024;
        if(empty($path)) $this->showLog('请指定备份文件存放目标', true);
        if(!is_dir($path)){
            mkdir($path, 0777, true) or $this->showLog('创建备份目录失败', true);
        }
        $this->path = $path;
        #  只备份某个表
        if(!empty($table)){
            $result = mysqli_query($this->db, 'show tables like \''.$table.'\'');
            $count = mysqli_num_rows($result);
            if(!$count){
                $this->showLog('表['. $table .']不存在,请先检查!', true);
            }
            $this->showLog('开始进行备份数据: ');
            #  写入备份文件头部描述信息
            $this->addHeader();
            #  写入表结构信息
            $this->showLog('处理备份表['. $table[0] .']中......');
            $this->addTable($table);
            #  写入表数据信息
            $this->addData($table);
        }else{
            $tables = mysqli_query($this->db, 'show tables');
            $count = mysqli_num_rows($tables);
            if(!$count){
                $this->showLog('读取数据库表失败!', true);
            }
            $this->showLog('开始进行备份数据: ');
            #  写入备份文件头部描述信息
            $this->addHeader();
            while($table = mysqli_fetch_array($tables)){
                #  写入表结构信息
                $this->showLog('处理备份表['. $table[0] .']中......');
                $this->addTable($table[0]);
                #  写入表数据信息
                $this->addData($table[0]);
            }
        }

        # 最后一份写入文件
        $filename = date('Ymd') . $this->config['database'] . '_' . $this->page .'.sql';
        $ste = $this->saveFile();
        if($ste){
            $msg  = '恭喜您,全部备份成功,共'. $this->page .'份文件'. PHP_EOL;
            $this->showLog($msg, true);
        }else{
            $msg = '备份失败,请重新备份'. PHP_EOL;
            $this->showLog($msg, true);
        }
    }

    #  ------------上:数据库导出-----------分割线----------下:数据库导入-------------

    /**
     * 数据库导入(主调用方法)
     * @access public
     * @param string $sqlfile [必须]sql文件目录
     * @param int $type       [可选]false单文件导入(默认),true多文件导入
     * @return string
     */
    public function import($sqlfile='', $type=false)
    {
        #  判断文件是否存在
        if(!file_exists($sqlfile)) $this->showLog('sql文件不存在!请检查', true);
        if($type === true){
            # 多文件导入(分卷)
            $this->showLog('暂时不支持分卷同时导入,请更换成单文件按顺序一个一个导入谢谢', true);
        }else{
            # 单文件导入
            $start_time = time();
            $this->showLog('开始导入数据库文件......');
            $f = fopen($sqlfile, 'rb');
            $sql = '';
            $table = '';
            while (!feof($f)){
                #  获取每一行数据
                $line = fgets($f);
                $line = trim($line);
                #  判断是不是注释,以--开头
                if(strpos($line, '--') === 0 || empty($line)) continue;
                #  判断是不是创建表语句,以CREATE开头
                if(strpos($line, 'CREATE') === 0 || strpos($line, 'create') === 0){
                    if($table) $this->showLog($table.':完成导入');
                    preg_match_all('/`(.*)`/', $line, $mat);
                    $table = empty(current(end($mat))) ? '': current(end($mat));
                    if($table) $this->showLog($table.':正在导入...');
                }
                #  如果结尾不是';'(即还不是一个完整的语句,需要先拼接)
                if(strrchr($line, ';') != ';'){
                    $sql .= $line;
                    continue;
                }else{
                    $sql .= $line;
                }
                #  执行sql语句
                if(!mysqli_query($this->db, $sql)){
                    $this->showLog(mysqli_error($this->db), true);
                }
                $sql = '';
            }
            fclose($f);
            $time = time() - $start_time;
            $this->showLog('全部导入完成:共花 '.$time.'');
        }


    }

    /**
     * 锁定数据库(以免备份或导入时出错)
     * @access private
     * @return null
     */
    private function lock($table, $op='write')
    {
        mysqli_query($this->db, 'lock tables ' . $table . ' ' . $op );
    }

    /**
     * 解锁数据库
     * @access private
     * @return null
     */
    private function unlock()
    {
        mysqli_query($this->db, 'unlock tables');
    }

    /**
     * 析构方法
     * @access private
     * @return null
     */
    public function __destruct()
    {
        if($this->db){
            mysqli_query($this->db, 'unlock tables');
            mysqli_close($this->db);
        }
    }

}









 浏览器启用弹出窗口过滤功能,将无法跳转到下载页。在浏览器地址栏右边符号提示处点击允许就可以了!
下载源码  
【温馨提示】源码包解压密码:www.youhutong.com

转载请注明来源地址:小川编程 » https://www.youhutong.com/index.php/article/index/234.html


  1、本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,下载后请24小时内删除。
  2、本站所有内容均不能保证其完整性,不能接受请勿购买或下载,如需完整程序,请去其官方购买正版使用
  3、本站联系方式Email:admin@youhutong.com ,收到邮件会第一时间处理。
  4、如侵犯到任何版权问题,请立即告知本站(立即在线告知),本站将及时删除并致以最深的歉意
( 0 )个小伙伴在吐槽
    登录帐号  如果已经登录请刷新! 发表我的评论
    表情