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');
?>
更多信息請(qǐng)查看IT技術(shù)專欄