本文實(shí)例講述了php實(shí)現(xiàn)MySQL數(shù)據(jù)庫備份類。分享給大家供大家參考。具體分析如下:這是一個(gè)非常簡(jiǎn)單的利用php來備份mysql數(shù)據(jù)庫的類文件,我們只要簡(jiǎn)單的配置好連接地址用戶名與數(shù)據(jù)庫即可
php備份數(shù)據(jù)庫類分享
- <?php
- /**
- *
- * @name php備份數(shù)據(jù)庫
- * @param string $DbHost 連接主機(jī)
- * @param string $DbUser 用戶名
- * @param string $DbPwd 連接密碼
- * @param string $DbName 要備份的數(shù)據(jù)庫
- * @param string $saveFileName 要保存的文件名, 默認(rèn)文件保存在當(dāng)前文件夾中,以日期作區(qū)分
- * @return Null
- * @example backupMySqlData('localhost', 'root', '123456', 'YourDbName');
- *
- */
- function backupMySqlData($DbHost, $DbUser, $DbPwd, $DbName, $saveFileName = '')
- {
- header("Content-type:text/html;charset=utf-8");
- error_reporting(0);
- set_time_limit(0);
- echo '數(shù)據(jù)備份中,請(qǐng)稍候......<br />';
- $link = mysql_connect($DbHost, $DbUser, $DbPwd) or die('數(shù)據(jù)庫連接失敗: ' . mysql_error());
- mysql_select_db($DbName) or die('數(shù)據(jù)庫連接失敗: ' . mysql_error());
- mysql_query('set names utf8');
- // 聲明變量
- $isDropInfo = '';
- $insertSQL = '';
- $row = array();
- $tables = array();
- $tableStructure = array();
- $fileName = ($saveFileName ? $saveFileName : 'MySQL_data_bakeup_') . date('YmdHis') . '.sql';
- // 枚舉該數(shù)據(jù)庫所有的表
- $res = mysql_query("SHOW TABLES FROM $DbName");
- while ($row = mysql_fetch_row($res)) {
- $tables[] = $row[0];
- }
- mysql_free_result($res);
- // 枚舉所有表的創(chuàng)建語句
- foreach ($tables as $val) {
- $res = mysql_query("show create table $val", $link);
- $row = mysql_fetch_row($res);
- $isDropInfo = "DROP TABLE IF EXISTS `" . $val . "`;/r/n";
- $tableStructure = $isDropInfo . $row[1] . ";/r/n";
- file_put_contents($fileName, $tableStructure, FILE_APPEND);
- mysql_free_result($res);
- }
- // 枚舉所有表的INSERT語句
- foreach ($tables as $val) {
- $res = mysql_query("select * from $val");
- // 沒有數(shù)據(jù)的表不執(zhí)行insert
- while ($row = mysql_fetch_row($res)) {
- $sqlStr = "INSERT INTO `".$val."` VALUES (";
- foreach($row as $v){
- $sqlStr .= "'$v',";
- }
- //去掉最后一個(gè)逗號(hào)
- $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 1);
- $sqlStr .= ");/r/n";
- file_put_contents($fileName, $sqlStr, FILE_APPEND);
- }
- mysql_free_result($res);
- }
- echo '數(shù)據(jù)備份成功!';
- }
- // 調(diào)用此方法
- backupMySqlData('localhost', 'root', '123456', 'YouDbName');
- ?>
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
|
新聞熱點(diǎn)
疑難解答