利用PHP實(shí)現(xiàn)一個(gè)MySQL備份和恢復(fù)程序
背景
由于客戶用的阿里云將要到期,現(xiàn)在要把項(xiàng)目交給政府,需要把項(xiàng)目和阿里云上的數(shù)據(jù)庫都轉(zhuǎn)到政府云,數(shù)據(jù)肯定要轉(zhuǎn)過去,但是阿里云導(dǎo)出數(shù)據(jù)有數(shù)量限制,導(dǎo)出不全,所以就要程序執(zhí)行下,生成sql文件,然后導(dǎo)入政府云數(shù)據(jù)庫。這樣我們就需要一個(gè)腳本執(zhí)行下,下面分享下具體實(shí)現(xiàn)過程。
操作類的封裝
為了程序的代碼重用,我們首先封裝個(gè)類來實(shí)現(xiàn)備份與備份恢復(fù)功能,為了節(jié)約時(shí)間,直接上代碼,不懂的可以看下注釋
<?php class DbOperate { var $conn; // 數(shù)據(jù)庫連接 var $database; // 所用數(shù)據(jù)庫 var $sqldir; // 數(shù)據(jù)庫備份文件夾 var $record; // sql語句變量 public $sqlContent = ""; /** * 實(shí)例化 * @param string $host $username $password $database $charset */ function __construct($host = 'localhost', $username = 'root', $password = '123456', $database = 'test', $charset = 'utf8') { $this->host = $host; $this->username = $username; $this->password = $password; $this->database = $database; $this->charset = $charset; // 數(shù)據(jù)庫連接 $this->conn = mysqli_connect ( $this->host, $this->username, $this->password ) or die ( "數(shù)據(jù)庫連接失敗!" ); // 數(shù)據(jù)庫選擇 mysql_select_db ( $this->database, $this->conn ) or die ( "無法打開數(shù)據(jù)庫" ); // 設(shè)置數(shù)據(jù)庫編碼 mysql_query ( 'SET NAMES ' . $this->charset, $this->conn ); } /** * 數(shù)據(jù)庫導(dǎo)出sql文件 * @param 備份表名稱(為空導(dǎo)出全部表),備份目錄(默認(rèn)目錄‘,./sql/'),文件大小(可選,默認(rèn)5000,即5M左右) */ function export($tablename = '', $dir, $size) { $dir = $dir ? $dir : './sql/'; $size = $size ? $size : 5000; $sql = ''; // 導(dǎo)出單張表 if (! empty ( $tablename )) { echo '正在導(dǎo)出表' . $tablename . PHP_EOL; // 插入數(shù)據(jù)庫信息 $sql = $this->get_mysql_info(); // 插入表結(jié)構(gòu)信息-獲取表的基本信息 $sql .= $this->get_table_structure ( $tablename ); // 插入數(shù)據(jù)-執(zhí)行查詢語句 $data = mysql_query ( "SELECT * FROM " . $tablename ); // 文件名前面部分 $filename = date ( 'YmdHis' ) . "_" . $tablename; // 字段數(shù)量 $num_fields = mysql_num_fields ( $data ); // 第一個(gè)sql文件 $no = 1; // 循環(huán)每條記錄 while ( $record = mysql_fetch_array ( $data ) ) { // 單條記錄 $sql .= $this->insert_record ( $tablename, $num_fields, $record ); // 如果大于分卷大小,則寫入文件 if (strlen ( $sql ) >= $size * 1000) { $file = $filename . "_num" . $no . ".sql"; if ($this->write_file ( $sql, $file, $dir )) { echo "表-" . $tablename . "-編號(hào)-" . $no . "-數(shù)據(jù)導(dǎo)出完成,生成SQL文件 $dir$filename".PHP_EOL; } else { echo "導(dǎo)出表-" . $tablename . "-失敗".PHP_EOL; } // 下一個(gè)SQL文件 $no ++; // 重置$sql變量為空,重新計(jì)算該變量大小 $sql = ""; } } // sql大小不夠 if ($sql != "") { $filename .= "_num" . $no . ".sql"; if ($this->write_file ( $sql, $filename, $dir )) { echo "表-" . $tablename . "-編號(hào)-" . $no . "-數(shù)據(jù)導(dǎo)出完成,生成sql文件 $dir$filename".PHP_EOL; } else { echo "表-" . $tablename . "-編號(hào)-" . $no . "-數(shù)據(jù)寫入失敗".PHP_EOL; } } } else { // 備份全部表 if ($tables = mysql_query ( "show table status from " . $this->database )) { echo "讀取數(shù)據(jù)庫結(jié)構(gòu)成功".PHP_EOL; } else { exit ( "讀取數(shù)據(jù)庫結(jié)構(gòu)成功" ).PHP_EOL; } // 插入dump信息 $sql .= $this->get_mysql_info(); // 文件名前面部分 $filename = date ( 'YmdHis' ) . "_all"; // 查出所有表 $tables = mysql_query ( 'SHOW TABLES' ); // SQL文件編號(hào) $no = 1; // 循環(huán)所有表 while ( $table = mysql_fetch_array ( $tables ) ) { echo '開始導(dǎo)出表:'.$table [0].PHP_EOL; // 獲取表名 $tablename = $table [0]; // 獲取表結(jié)構(gòu) $sql .= $this->get_table_structure ( $tablename ); $data = mysql_query ( "SELECT * FROM " . $tablename ); $num_fields = mysql_num_fields ( $data ); // 循環(huán)每條記錄 while ( $record = mysql_fetch_array ( $data ) ) { // 單條記錄 $sql .= $this->insert_record ( $tablename, $num_fields, $record ); // 如果達(dá)到定義的文件大小,就寫入文件 if (strlen ( $sql ) >= $size * 1000) { $file = $filename . "_num" . $no . ".sql"; // 寫入文件 if ($this->write_file ( $sql, $file, $dir )) { echo "表-" . $tablename . "-編號(hào)-" . $no . "-數(shù)據(jù)寫入成功-$dir$file".PHP_EOL; } else { echo "表-" . $tablename . "-編號(hào)-" . $no . "-數(shù)據(jù)寫入失敗".PHP_EOL; } // 下一個(gè)sql文件 $no ++; // 重置$sql變量為空,重新計(jì)算寫入sql大小 $sql = ""; } } } // sql大小不夠分卷大小 if ($sql != "") { $filename .= "_num" . $p . ".sql"; if ($this->write_file ( $sql, $filename, $dir )) { echo "-編號(hào)-" . $no . "-數(shù)據(jù)導(dǎo)出完成,生成SQL文件 $dir$filename".PHP_EOL; } else { echo "-編號(hào)-" . $no . "-寫入失敗".PHP_EOL; } } } } /** * 獲取mysql基礎(chǔ)信息 * * @return string */ private function get_mysql_info() { $value = ''; $value .= '--' . "\n"; $value .= '-- 主機(jī): ' . $this->host . "\n"; $value .= '-- 生成日期: ' . date ( 'Y' ) . ' 年 ' . date ( 'm' ) . ' 月 ' . date ( 'd' ) . ' 日 ' . date ( 'H:i' ) . "\n"; $value .= '-- MySQL版本: ' . mysql_get_server_info () . "\n"; $value .= "\n"; $value .= '--' . "\n"; $value .= '-- 數(shù)據(jù)庫: `' . $this->database . '`' . "\n"; $value .= '--' . "\n" . "\n"; $value .= '-- -------------------------------------------------------'; $value .= "\n" . "\n"; return $value; } /** * 獲取表結(jié)構(gòu) * @param $table * @return string */ private function get_table_structure($table) { $sql = ''; $sql .= "--" . "\n"; $sql .= "-- 表的結(jié)構(gòu)" . $table . "\n"; $sql .= "--" . "\n" . "\n"; // 如果存在則刪除表 $sql .= "DROP TABLE IF EXISTS `" . $table . '`' . ";" . "\n"; // 獲取詳細(xì)表信息 $res = mysql_query ( 'SHOW CREATE TABLE `' . $table . '`' ); $row = mysql_fetch_array ( $res ); $sql .= $row [1]; $sql .= ";" . "\n"; // 加上 $sql .= "\n"; $sql .= "--" . "\n"; $sql .= "-- 轉(zhuǎn)存表中的數(shù)據(jù) " . $table . "\n"; $sql .= "--" . "\n"; $sql .= "\n"; return $sql; } /** * 插入單條記錄 * * @param string $table * @param int $num_fields * @param array $record * @return string */ private function insert_record($table, $num_fields, $record) { // sql字段逗號(hào)分割 $comma = ""; $insert .= "INSERT INTO `" . $table . "` VALUES("; // 循環(huán)每個(gè)子段下面的內(nèi)容 for($i = 0; $i < $num_fields; $i ++) { $insert .= ($comma . "'" . mysql_escape_string ( $record [$i] ) . "'"); $comma = ","; } $insert .= ");" . "\n"; return $insert; } /** * 寫入文件 * * @param string $sql * @param string $filename * @param string $dir * @return boolean */ private function write_file($sql, $filename, $dir) { $dir = $dir ? $dir : './sql/'; // 不存在文件夾則創(chuàng)建 if (! file_exists ( $dir )) { mkdir ( $dir ); } $re = true; if (! @$fp = fopen ( $dir . $filename, "w+" )) { $re = false; echo "打開文件失??!"; } if (! @fwrite ( $fp, $sql )) { $re = false; echo "寫入文件失敗,請文件是否可寫"; } if (! @fclose ( $fp )) { $re = false; echo "關(guān)閉文件失敗!"; } return $re; } /** * 導(dǎo)入sql文件數(shù)據(jù) * 說明:sql文件格式20120516211738_all_no1.sql * 參數(shù):sql文件路徑(必填) * * @param string $sqlfile */ function import($sqlfile) { // 檢測文件是否存在 if (! file_exists ( $sqlfile )) { exit ( "文件不存在!請檢查" ); } $this->lock ( $this->database ); // 獲取數(shù)據(jù)庫存儲(chǔ)位置 $sqlpath = pathinfo ( $sqlfile ); $this->sqldir = $sqlpath ['dirname']; $volume = explode ( "_no", $sqlfile ); $volume_path = $volume [0]; echo "正在導(dǎo)入sql數(shù)據(jù),請稍等!".PHP_EOL; if (empty ( $volume [1] )) { echo "正在導(dǎo)入sql:" . $sqlfile . PHP_EOL; if ($this->_import ( $sqlfile )) { echo "數(shù)據(jù)導(dǎo)入成功!"; } else { exit ( '數(shù)據(jù)導(dǎo)入失??!' ); } } else { $volume_id = explode ( ".sq", $volume [1] ); $volume_id = intval ( $volume_id [0] ); while ( $volume_id ) { $tmpfile = $volume_path . "_no" . $volume_id . ".sql"; // 存在其他分卷,繼續(xù)執(zhí)行 if (file_exists ( $tmpfile )) { // 執(zhí)行導(dǎo)入方法 echo "正在導(dǎo)入分卷$volume_id:" . $tmpfile . PHP_EOL; if ($this->_import ( $tmpfile )) { } else { exit ( "導(dǎo)入$volume_id:" . $tmpfile . '失??!可能是數(shù)據(jù)庫結(jié)構(gòu)已損壞!請嘗試從編號(hào)1開始導(dǎo)入' ); } } else { echo "此文件數(shù)據(jù)全部導(dǎo)入成功!".PHP_EOL; return; } $volume_id++; } } } /** * 將sql導(dǎo)入到數(shù)據(jù)庫(普通導(dǎo)入) * * @param string $sqlfile * @return boolean */ private function _import($sqlfile) { // sql文件包含的sql語句數(shù)組 $sqls = array (); $f = fopen ( $sqlfile, "rb" ); // 創(chuàng)建表緩沖變量 $create = ''; while ( ! feof ( $f ) ) { // 讀取每一行sql $line = fgets ( $f ); // 如果包含'-- '等注釋,或?yàn)榭瞻仔?,則跳過 if (trim ( $line ) == '' || preg_match ( '/--*?/', $line, $match )) { continue; } // 如果結(jié)尾包含';'(即為一個(gè)完整的sql語句,這里是插入語句),并且不包含'ENGINE='(即創(chuàng)建表的最后一句), if (! preg_match ( '/;/', $line, $match ) || preg_match ( '/ENGINE=/', $line, $match )) { // 將本次sql語句與創(chuàng)建表sql連接存起來 $create .= $line; // 如果包含了創(chuàng)建表的最后一句 if (preg_match ( '/ENGINE=/', $create, $match )) { // 則將其合并到sql數(shù)組 $sqls [] = $create; // 清空當(dāng)前,準(zhǔn)備下一個(gè)表的創(chuàng)建 $create = ''; } // 跳過本次 continue; } $sqls [] = $line; } fclose ( $f ); // 循環(huán)sql語句數(shù)組,分別執(zhí)行 foreach ( $sqls as $sql ) { str_replace ( "\n", "", $sql ); if (! mysql_query ( trim ( $sql ) )) { echo mysql_error (); return false; } } return true; } // 關(guān)閉數(shù)據(jù)庫連接 private function close() { mysql_close ( $this->conn ); } // 鎖定數(shù)據(jù)庫,以免備份或?qū)霑r(shí)出錯(cuò) 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; } // 析構(gòu) function __destruct() { mysql_query ( "unlock tables", $this->conn ); mysql_close ( $this->conn ); } } ?>
調(diào)用操作類,實(shí)現(xiàn)導(dǎo)出sql、導(dǎo)入數(shù)據(jù)
<?php include 'DbOperate.php'; /** * 數(shù)據(jù)庫導(dǎo)出完整數(shù)據(jù) * @param 主機(jī)名、數(shù)據(jù)庫賬號(hào)、數(shù)據(jù)庫密碼、數(shù)據(jù)庫名、編碼格式 */ $db = new DbOperate ( '主機(jī)名','數(shù)據(jù)庫賬號(hào)','數(shù)據(jù)庫密碼','數(shù)據(jù)庫名','編碼格式' ); // 參數(shù):備份哪個(gè)表(可選),備份目錄(可選,默認(rèn)為backup),分卷大小(可選,默認(rèn)2000,即2M) $db->export('',"/data/wwwtest/mysql_backup/sql/"); /** * 數(shù)據(jù)庫導(dǎo)入 * @param sql文件路徑 */ //$db->import ( 'sql文件路徑'); $db->close();//關(guān)閉數(shù)據(jù)庫連接
執(zhí)行以上代碼,就可以實(shí)現(xiàn)數(shù)據(jù)庫全部數(shù)據(jù)導(dǎo)出了,如果想要導(dǎo)出某張表,第一個(gè)參數(shù)寫上表名稱即可。那么將導(dǎo)出的數(shù)據(jù)導(dǎo)入新的數(shù)據(jù)庫又該怎么辦呢?直接將上面的程序改下數(shù)據(jù)庫連接配置,將調(diào)用導(dǎo)出export的方法注釋掉,打開下面的import方法,運(yùn)行程序,就可以實(shí)現(xiàn)數(shù)據(jù)的導(dǎo)入了。
總結(jié)
MySQL數(shù)據(jù)庫導(dǎo)出,雖然也可以用數(shù)據(jù)庫工具實(shí)現(xiàn),例如navicat等,但是對(duì)于阿里云的數(shù)據(jù)庫,連接需要設(shè)置白名單,而自己公司的公網(wǎng)ip又經(jīng)常變,操作起來就會(huì)很麻煩,所以寫個(gè)腳本還是有必要的。由于工作中有用到,記錄下實(shí)現(xiàn)過程,把工作中的經(jīng)驗(yàn)記錄下來,加深下印象。同時(shí)也希望能夠幫到有需要的同學(xué)。
到此這篇關(guān)于利用PHP實(shí)現(xiàn)一個(gè)MySQL備份和恢復(fù)程序的文章就介紹到這了,更多相關(guān)PHP實(shí)現(xiàn)MySQL備份和恢復(fù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP jpgraph庫的配置及生成統(tǒng)計(jì)圖表:折線圖、柱狀圖、餅狀圖
本篇文章主要介紹了PHP jpgraph庫的配置及生成統(tǒng)計(jì)圖表:折線圖、柱狀圖、餅狀圖等的相關(guān)知識(shí)。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-05-05PHP/Javascript/CSS/jQuery常用知識(shí)大全詳細(xì)整理
PHP/Javascript/CSS/jQuery常用知識(shí)大全詳細(xì)整理(原創(chuàng))感興趣的朋友可以參考下2013-01-01php動(dòng)態(tài)函數(shù)調(diào)用方法
本文主要給大家介紹了php中動(dòng)態(tài)調(diào)用函數(shù)的方法,實(shí)例分析了php動(dòng)態(tài)函數(shù)的實(shí)現(xiàn)原理與具體實(shí)現(xiàn)步驟,需要的朋友可以參考下2015-05-05php 廣告調(diào)用類代碼(支持Flash調(diào)用)
php 廣告調(diào)用類代碼(支持Flash調(diào)用),非常方便php頁面中加載廣告。需要的朋友可以參考下。2011-08-08