php備份資料庫類的方法
PHP是一種 HTML 內嵌式的語言,是一種在伺服器端執行的嵌入HTML文件的指令碼語言,語言的風格有類似於C語言,被廣泛地運用。大家知道php備份資料庫類嗎?下面我們就給大家詳細介紹一下吧!我們積累了一些經驗,在此拿出來與大家分享下,請大家互相指正。
php備份資料庫類分享1
/**
*
* @name php備份資料庫
* @param string $DbHost 連線主機
* @param string $DbUser 使用者名稱
* @param string $DbPwd 連線密碼
* @param string $DbName 要備份的資料庫
* @param string $saveFileName 要儲存的檔名, 預設檔案儲存在當前資料夾中,以日期作區分
* @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 '資料備份中,請稍候......
';
$link = mysql_connect($DbHost, $DbUser, $DbPwd) or die('資料庫連線失敗: ' . mysql_error());
mysql_select_db($DbName) or die('資料庫連線失敗: ' . mysql_error());
mysql_query('set names utf8');
// 宣告變數
$isDropInfo = '';
$SQL = '';
$row = array();
$tables = array();
$tableStructure = array();
$fileName = ($saveFileName ? $saveFileName : 'MySQL_data_bakeup_') . date('YmdHis') . '';
// 列舉該資料庫所有的'表
$res = mysql_query("SHOW TABLES FROM $DbName");
while ($row = mysql_fetch_row($res)) {
$tables[] = $row[0];
}
mysql_free_result($res);
// 列舉所有表的建立語句
foreach ($tables as $val) {
$res = mysql_query("show create table $val", $link);
$row = mysql_fetch_row($res);
$isDropInfo = "DROP TABLE IF EXISTS `" . $val . "`;rn";
$tableStructure = $isDropInfo . $row[1] . ";rn";
file_put_contents($fileName, $tableStructure, FILE_APPEND);
mysql_free_result($res);
}
// 列舉所有表的INSERT語句
foreach ($tables as $val) {
$res = mysql_query("select * from $val");
// 沒有資料的表不執行
while ($row = mysql_fetch_row($res)) {
$sqlStr = "INSERT INTO `".$val."` VALUES (";
foreach($row as $v){
$sqlStr .= "'$v',";
}
//去掉最後一個逗號
$sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 1);
$sqlStr .= ");rn";
file_put_contents($fileName, $sqlStr, FILE_APPEND);
}
mysql_free_result($res);
}
echo '資料備份成功!';
}
// 呼叫此方法
backupMySqlData('localhost', 'root', '123456', 'YouDbName');
?>