功能特色
- 支援多資料庫、多表備份。
- 自動建立日期目錄(
databak/YYYYMMDD)。
- 產出
.sql 檔含 DROP TABLE IF EXISTS、CREATE TABLE、INSERT 完整結構與資料。
- 自動清理 N 天前備份(預設 5 天)。
- UTF-8 編碼、錯誤記錄。
核心類別 dbmysql
class dbmysql {
public static $dbhost = 'localhost';
public static $dbname;
public static $dbuser = 'root';
public static $dbpass;
public static $charset = 'utf8';
public static $DB = null;
public function __construct() {
self::$dbhost = $GLOBALS['cfg_dbhost'];
self::$dbname = $GLOBALS['cfg_dbname'];
self::$dbuser = $GLOBALS['cfg_dbuser'];
self::$dbpass = $GLOBALS['cfg_dbpwd'];
self::$charset= $GLOBALS['cfg_db_language'];
self::connect();
}
// connect(), getTablesName(), getFields(), fetch_array(), fetch_assoc(), sqlError(), close()...
}
備份執行腳本
<?php
header("Content-Type: text/html; charset=utf-8");
require_once 'dbmysql.class.php';
$db = new dbmysql();
$tables = $db->getTablesName();
$bakDir = "databak/" . date("Ymd");
makedir($bakDir); // 遞迴建立目錄
// 清理 5 天前備份
$handle = opendir(getcwd() . "/databak/");
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_dir("$bakDir/../$file")) {
if (date("Ymd") - $file > 5) delDirAndFile("$bakDir/../$file");
}
}
closedir($handle);
foreach ($tables as $t) {
// 取得建表語句
$create = $db->fetch_array("SHOW CREATE TABLE `$t`");
$sql = "/* Time: " . date("Y-m-d H:i:s") . " */\n";
$sql .= "DROP TABLE IF EXISTS `$t`;\n" . $create['Create Table'] . ";\n\n";
// 取得所有資料
$rows = $db->fetch_assoc("SELECT * FROM `$t`");
foreach ($rows as $row) {
$vals = array_map('addslashes', array_values($row));
$sql .= "INSERT INTO `$t` VALUES ('" . implode("','", $vals) . "');\n";
}
$sql .= "\n";
filein($bakDir, $t, $sql);
}
echo "備份完成:$bakDir";
?>
輔助函數
function makedir($path) { /* 遞迴 mkdir */ }
function delDirAndFile($dir) { /* 遞迴刪除目錄與檔案 */ }
function filein($dir, $table, $content) { /* fwrite 存檔 */ }
改進建議
- 改用
mysqldump 呼叫(exec())效能更高、支援大表分塊。
- 加入
gzip 壓縮:gzencode($sql) 存 .sql.gz。
- 加入備份驗證:
CHECKSUM TABLE 比對。
- 記錄備份日誌至資料表/檔案,支援監控告警。