天天看點

推薦一個PHP的MySQL資料庫備份還原類

在GitHub上發現的一個PHP的MySQL資料庫備份還原類,寫的不錯,目測用的人似乎不多,好東西就推廣一下哈

導出後的sql檔案格式如下:

--
-- MySQL database dump
-- Created by DBManage class, Power By yanue. 
-- http://www.yanue.net 
--
-- 主機: localhost
-- 生成日期: 2012 年  10 月 06 日 22:32
-- MySQL版本: 5.1.50-community
-- PHP 版本: 5.3.9-ZS5.6.0

--
-- 資料庫: `test`
--

-- -------------------------------------------------------

--
-- 表的結構aa
--

DROP TABLE IF EXISTS `aa`;
CREATE TABLE `aa` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

--
-- 轉存表中的資料 aa
--

INSERT INTO `aa` VALUES('1','<p id="test"><span class='hahh' style="line-height:;">我是測試資料 呵呵</span></p>');
           

下面是類代碼:

*----------------------------------------------------------------------
 */
class DbManage {
    var $db; // 資料庫連接配接
    var $database; // 所用資料庫
    var $sqldir; // 資料庫備份檔案夾
    // 換行符
    private $ds = "\n";
    // 存儲SQL的變量
    public $sqlContent = "";
    // 每條sql語句的結尾符
    public $sqlEnd = ";";

    /**
     * 初始化
     *
     * @param string $host
     * @param string $username
     * @param string $password
     * @param string $database
     * @param string $charset
     */
    function __construct($host = 'localhost', $username = 'root', $password = '', $database = 'test', $charset = 'utf8') {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->database = $database;
        $this->charset = $charset;
        set_time_limit();//無時間限制
@ob_end_flush();
        // 連接配接資料庫
        $this->db = @mysql_connect ( $this->host, $this->username, $this->password ) or die( '<p class="dbDebug"><span class="err">Mysql Connect Error : </span>'.mysql_error().'</p>');
        // 選擇使用哪個資料庫
        mysql_select_db ( $this->database, $this->db ) or die('<p class="dbDebug"><span class="err">Mysql Connect Error:</span>'.mysql_error().'</p>');
        // 資料庫編碼方式
        mysql_query ( 'SET NAMES ' . $this->charset, $this->db );

    }

    /*
     * 新增查詢資料庫表
     */
    function getTables() {
        $res = mysql_query ( "SHOW TABLES" );
        $tables = array ();
        while ( $row = mysql_fetch_array ( $res ) ) {
            $tables [] = $row [];
        }
        return $tables;
    }

    /*
     *
     * ------------------------------------------資料庫備份start----------------------------------------------------------
     */

    /**
     * 資料庫備份
     * 參數:備份哪個表(可選),備份目錄(可選,預設為backup),分卷大小(可選,預設2000,即2M)
     *
     * @param $string $dir
     * @param int $size
     * @param $string $tablename
     */
    function backup($tablename = '', $dir, $size) {
        $dir = $dir ? $dir : './backup/';
        // 建立目錄
        if (! is_dir ( $dir )) {
            mkdir ( $dir, , true ) or die ( '建立檔案夾失敗' );
        }
        $size = $size ? $size : ;
        $sql = '';
        // 隻備份某個表
        if (! empty ( $tablename )) {
            if(@mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tablename."'")) == ) {
             } else {
                $this->_showMsg('表-<b>' . $tablename .'</b>-不存在,請檢查!',true);
                die();
            }
            $this->_showMsg('正在備份表 <span class="imp">' . $tablename.'</span>');
            // 插入dump資訊
            $sql = $this->_retrieve ();
            // 插入表結構資訊
            $sql .= $this->_insert_table_structure ( $tablename );
            // 插入資料
            $data = mysql_query ( "select * from " . $tablename );
            // 檔案名前面部分
            $filename = date ( 'YmdHis' ) . "_" . $tablename;
            // 字段數量
            $num_fields = mysql_num_fields ( $data );
            // 第幾分卷
            $p = ;
            // 循環每條記錄
            while ( $record = mysql_fetch_array ( $data ) ) {
                // 單條記錄
                $sql .= $this->_insert_record ( $tablename, $num_fields, $record );
                // 如果大于分卷大小,則寫入檔案
                if (strlen ( $sql ) >= $size * ) {
                    $file = $filename . "_v" . $p . ".sql";
                    if ($this->_write_file ( $sql, $file, $dir )) {
                        $this->_showMsg("表-<b>" . $tablename . "</b>-卷-<b>" . $p . "</b>-資料備份完成,備份檔案 [ <span class='imp'>" .$dir . $file ."</span> ]");
                    } else {
                        $this->_showMsg("備份表 -<b>" . $tablename . "</b>- 失敗",true);
                        return false;
                    }
                    // 下一個分卷
                    $p ++;
                    // 重置$sql變量為空,重新計算該變量大小
                    $sql = "";
                }
            }
            // 及時清除資料
            unset($data,$record);
            // sql大小不夠分卷大小
            if ($sql != "") {
                $filename .= "_v" . $p . ".sql";
                if ($this->_write_file ( $sql, $filename, $dir )) {
                    $this->_showMsg( "表-<b>" . $tablename . "</b>-卷-<b>" . $p . "</b>-資料備份完成,備份檔案 [ <span class='imp'>" .$dir . $filename ."</span> ]");
                } else {
                    $this->_showMsg("備份卷-<b>" . $p . "</b>-失敗<br />");
                    return false;
                }
            }
            $this->_showMsg("恭喜您! <span class='imp'>備份成功</span>");
        } else {
            $this->_showMsg('正在備份');
            // 備份全部表
            if ($tables = mysql_query ( "show table status from " . $this->database )) {
                $this->_showMsg("讀取資料庫結構成功!");
            } else {
                $this->_showMsg("讀取資料庫結構失敗!");
                exit (  );
            }
            // 插入dump資訊
            $sql .= $this->_retrieve ();
            // 檔案名前面部分
            $filename = date ( 'YmdHis' ) . "_all";
            // 查出所有表
            $tables = mysql_query ( 'SHOW TABLES' );
            // 第幾分卷
            $p = ;
            // 循環所有表
            while ( $table = mysql_fetch_array ( $tables ) ) {
                // 擷取表名
                $tablename = $table [];
                // 擷取表結構
                $sql .= $this->_insert_table_structure ( $tablename );
                $data = mysql_query ( "select * from " . $tablename );
                $num_fields = mysql_num_fields ( $data );

                // 循環每條記錄
                while ( $record = mysql_fetch_array ( $data ) ) {
                    // 單條記錄
                    $sql .= $this->_insert_record ( $tablename, $num_fields, $record );
                    // 如果大于分卷大小,則寫入檔案
                    if (strlen ( $sql ) >= $size * ) {

                        $file = $filename . "_v" . $p . ".sql";
                        // 寫入檔案
                        if ($this->_write_file ( $sql, $file, $dir )) {
                            $this->_showMsg("-卷-<b>" . $p . "</b>-資料備份完成,備份檔案 [ <span class='imp'>".$dir.$file."</span> ]");
                        } else {
                            $this->_showMsg("卷-<b>" . $p . "</b>-備份失敗!",true);
                            return false;
                        }
                        // 下一個分卷
                        $p ++;
                        // 重置$sql變量為空,重新計算該變量大小
                        $sql = "";
                    }
                }
            }
            // sql大小不夠分卷大小
            if ($sql != "") {
                $filename .= "_v" . $p . ".sql";
                if ($this->_write_file ( $sql, $filename, $dir )) {
                    $this->_showMsg("-卷-<b>" . $p . "</b>-資料備份完成,備份檔案 [ <span class='imp'>".$dir.$filename."</span> ]");
                } else {
                    $this->_showMsg("卷-<b>" . $p . "</b>-備份失敗",true);
                    return false;
                }
            }
            $this->_showMsg("恭喜您! <span class='imp'>備份成功</span>");
        }
    }

    //  及時輸出資訊
    private function _showMsg($msg,$err=false){
        $err = $err ? "<span class='err'>ERROR:</span>" : '' ;
        echo "<p class='dbDebug'>".$err . $msg."</p>";
        flush();

    }

    /**
     * 插入資料庫備份基礎資訊
     *
     * @return string
     */
    private function _retrieve() {
        $value = '';
        $value .= '--' . $this->ds;
        $value .= '-- MySQL database dump' . $this->ds;
        $value .= '-- Created by DbManage class, Power By yanue. ' . $this->ds;
        $value .= '-- http://yanue.net ' . $this->ds;
        $value .= '--' . $this->ds;
        $value .= '-- 主機: ' . $this->host . $this->ds;
        $value .= '-- 生成日期: ' . date ( 'Y' ) . ' 年  ' . date ( 'm' ) . ' 月 ' . date ( 'd' ) . ' 日 ' . date ( 'H:i' ) . $this->ds;
        $value .= '-- MySQL版本: ' . mysql_get_server_info () . $this->ds;
        $value .= '-- PHP 版本: ' . phpversion () . $this->ds;
        $value .= $this->ds;
        $value .= '--' . $this->ds;
        $value .= '-- 資料庫: `' . $this->database . '`' . $this->ds;
        $value .= '--' . $this->ds . $this->ds;
        $value .= '-- -------------------------------------------------------';
        $value .= $this->ds . $this->ds;
        return $value;
    }

    /**
     * 插入表結構
     *
     * @param unknown_type $table
     * @return string
     */
    private function _insert_table_structure($table) {
        $sql = '';
        $sql .= "--" . $this->ds;
        $sql .= "-- 表的結構" . $table . $this->ds;
        $sql .= "--" . $this->ds . $this->ds;

        // 如果存在則删除表
        $sql .= "DROP TABLE IF EXISTS `" . $table . '`' . $this->sqlEnd . $this->ds;
        // 擷取詳細表資訊
        $res = mysql_query ( 'SHOW CREATE TABLE `' . $table . '`' );
        $row = mysql_fetch_array ( $res );
        $sql .= $row [];
        $sql .= $this->sqlEnd . $this->ds;
        // 加上
        $sql .= $this->ds;
        $sql .= "--" . $this->ds;
        $sql .= "-- 轉存表中的資料 " . $table . $this->ds;
        $sql .= "--" . $this->ds;
        $sql .= $this->ds;
        return $sql;
    }

    /**
     * 插入單條記錄
     *
     * @param string $table
     * @param int $num_fields
     * @param array $record
     * @return string
     */
    private function _insert_record($table, $num_fields, $record) {
        // sql字段逗号分割
        $insert = '';
        $comma = "";
        $insert .= "INSERT INTO `" . $table . "` VALUES(";
        // 循環每個子段下面的内容
        for($i = ; $i < $num_fields; $i ++) {
            $insert .= ($comma . "'" . mysql_escape_string ( $record [$i] ) . "'");
            $comma = ",";
        }
        $insert .= ");" . $this->ds;
        return $insert;
    }

    /**
     * 寫入檔案
     *
     * @param string $sql
     * @param string $filename
     * @param string $dir
     * @return boolean
     */
    private function _write_file($sql, $filename, $dir) {
        $dir = $dir ? $dir : './backup/';
        // 建立目錄
        if (! is_dir ( $dir )) {
            mkdir ( $dir, , true );
        }
        $re = true;
        if (! @$fp = fopen ( $dir . $filename, "w+" )) {
            $re = false;
            $this->_showMsg("打開sql檔案失敗!",true);
        }
        if (! @fwrite ( $fp, $sql )) {
            $re = false;
            $this->_showMsg("寫入sql檔案失敗,請檔案是否可寫",true);
        }
        if (! @fclose ( $fp )) {
            $re = false;
            $this->_showMsg("關閉sql檔案失敗!",true);
        }
        return $re;
    }

    /*
     *
     * -------------------------------上:資料庫導出-----------分割線----------下:資料庫導入--------------------------------
     */

    /**
     * 導入備份資料
     * 說明:分卷檔案格式20120516211738_all_v1.sql
     * 參數:檔案路徑(必填)
     *
     * @param string $sqlfile
     */
    function restore($sqlfile) {
        // 檢測檔案是否存在
        if (! file_exists ( $sqlfile )) {
            $this->_showMsg("sql檔案不存在!請檢查",true);
            exit ();
        }
        $this->lock ( $this->database );
        // 擷取資料庫存儲位置
        $sqlpath = pathinfo ( $sqlfile );
        $this->sqldir = $sqlpath ['dirname'];
        // 檢測是否包含分卷,将類似20120516211738_all_v1.sql從_v分開,有則說明有分卷
        $volume = explode ( "_v", $sqlfile );
        $volume_path = $volume [];
        $this->_showMsg("請勿重新整理及關閉浏覽器以防止程式被中止,如有不慎!将導緻資料庫結構受損");
        $this->_showMsg("正在導入備份資料,請稍等!");
        if (empty ( $volume [] )) {
            $this->_showMsg ( "正在導入sql:<span class='imp'>" . $sqlfile . '</span>');
            // 沒有分卷
            if ($this->_import ( $sqlfile )) {
                $this->_showMsg( "資料庫導入成功!");
            } else {
                 $this->_showMsg('資料庫導入失敗!',true);
                exit ();
            }
        } else {
            // 存在分卷,則擷取目前是第幾分卷,循環執行餘下分卷
            $volume_id = explode ( ".sq", $volume [] );
            // 目前分卷為$volume_id
            $volume_id = intval ( $volume_id [] );
            while ( $volume_id ) {
                $tmpfile = $volume_path . "_v" . $volume_id . ".sql";
                // 存在其他分卷,繼續執行
                if (file_exists ( $tmpfile )) {
                    // 執行導入方法
                    $this->msg .= "正在導入分卷 $volume_id :<span style='color:#f00;'>" . $tmpfile . '</span><br />';
                    if ($this->_import ( $tmpfile )) {

                    } else {
                        $volume_id = $volume_id ? $volume_id :;
                        exit ( "導入分卷:<span style='color:#f00;'>" . $tmpfile . '</span>失敗!可能是資料庫結構已損壞!請嘗試從分卷1開始導入' );
                    }
                } else {
                    $this->msg .= "此分卷備份全部導入成功!<br />";
                    return;
                }
                $volume_id ++;
            }
        }if (empty ( $volume [] )) {
            $this->_showMsg ( "正在導入sql:<span class='imp'>" . $sqlfile . '</span>');
            // 沒有分卷
            if ($this->_import ( $sqlfile )) {
                $this->_showMsg( "資料庫導入成功!");
            } else {
                 $this->_showMsg('資料庫導入失敗!',true);
                exit ();
            }
        } else {
            // 存在分卷,則擷取目前是第幾分卷,循環執行餘下分卷
            $volume_id = explode ( ".sq", $volume [] );
            // 目前分卷為$volume_id
            $volume_id = intval ( $volume_id [] );
            while ( $volume_id ) {
                $tmpfile = $volume_path . "_v" . $volume_id . ".sql";
                // 存在其他分卷,繼續執行
                if (file_exists ( $tmpfile )) {
                    // 執行導入方法
                    $this->msg .= "正在導入分卷 $volume_id :<span style='color:#f00;'>" . $tmpfile . '</span><br />';
                    if ($this->_import ( $tmpfile )) {

                    } else {
                        $volume_id = $volume_id ? $volume_id :;
                        exit ( "導入分卷:<span style='color:#f00;'>" . $tmpfile . '</span>失敗!可能是資料庫結構已損壞!請嘗試從分卷1開始導入' );
                    }
                } else {
                    $this->msg .= "此分卷備份全部導入成功!<br />";
                    return;
                }
                $volume_id ++;
            }
        }
    }

    /**
     * 将sql導入到資料庫(普通導入)
     *
     * @param string $sqlfile
     * @return boolean
     */
    private function _import($sqlfile) {
        // sql檔案包含的sql語句數組
        $sqls = array ();
        $f = fopen ( $sqlfile, "rb" );
        // 建立表緩沖變量
        $create_table = '';
        while ( ! feof ( $f ) ) {
            // 讀取每一行sql
            $line = fgets ( $f );
            // 這一步為了将建立表合成完整的sql語句
            // 如果結尾沒有包含';'(即為一個完整的sql語句,這裡是插入語句),并且不包含'ENGINE='(即建立表的最後一句)
            if (! preg_match ( '/;/', $line ) || preg_match ( '/ENGINE=/', $line )) {
                // 将本次sql語句與建立表sql連接配接存起來
                $create_table .= $line;
                // 如果包含了建立表的最後一句
                if (preg_match ( '/ENGINE=/', $create_table)) {
                    //執行sql語句建立表
                    $this->_insert_into($create_table);
                    // 清空目前,準備下一個表的建立
                    $create_table = '';
                }
                // 跳過本次
                continue;
            }
            //執行sql語句
            $this->_insert_into($line);
        }
        fclose ( $f );
        return true;
    }

    //插入單條sql語句
    private function _insert_into($sql){
        if (! mysql_query ( trim ( $sql ) )) {
            $this->msg .= mysql_error ();
            return false;
        }
    }

    /*
     * -------------------------------資料庫導入end---------------------------------
     */

    // 關閉資料庫連接配接
    private function close() {
        mysql_close ( $this->db );
    }

    // 鎖定資料庫,以免備份或導入時出錯
    private function lock($tablename, $op = "WRITE") {
        if (mysql_query ( "lock tables " . $tablename . " " . $op ))
            return true;
        else
            return false;
    }

    // 解鎖
    private function unlock() {
        if (mysql_query ( "unlock tables" ))
            return true;
        else
            return false;
    [}](http://www.yanue.net/archives/174.html)

    // 析構
    function __destruct() {
        if($this->db){
            mysql_query ( "unlock tables", $this->db );
            mysql_close ( $this->db );
        }
    }

}
?>
           
半葉寒羽的DBManage class,出處:https://github.com/yanue/Dbmanage