在PHP中實現數據庫備份與恢復,通常涉及以下幾個步驟:
<?php
// 數據庫配置
$dbHost = 'localhost';
$dbName = 'your_database';
$dbUser = 'your_username';
$dbPass = 'your_password';
// 創建數據庫連接
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 獲取數據庫所有表的名稱
$tables = [];
$result = $conn->query("SHOW TABLES");
while ($row = $result->fetch_array()) {
$tables[] = $row[0];
}
// 導出數據
$backupFile = 'backup-' . date('Y-m-d-H-i-s') . '.sql';
$backupSql = "SET FOREIGN_KEY_CHECKS=0;\n\n";
foreach ($tables as $table) {
$result = $conn->query("SHOW CREATE TABLE `$table`");
$row = $result->fetch_array();
$backupSql .= $row[1] . ";\n\n";
$result = $conn->query("SELECT * FROM `$table`");
$columns = $result->num_fields;
while ($row = $result->fetch_array()) {
$backupSql .= "INSERT INTO `$table` VALUES(";
for ($i = 0; $i < $columns; $i++) {
$backupSql .= "'" . mysqli_real_escape_string($conn, $row[$i]) . "', ";
}
$backupSql = rtrim($backupSql, ', ') . ");\n";
}
}
$backupSql .= "\nSET FOREIGN_KEY_CHECKS=1;";
// 保存到文件
file_put_contents($backupFile, $backupSql);
echo "數據庫備份成功: " . $backupFile;
$conn->close();
?>
<?php
// 數據庫配置
$dbHost = 'localhost';
$dbName = 'your_database';
$dbUser = 'your_username';
$dbPass = 'your_password';
// 創建數據庫連接
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 讀取備份文件
$backupFile = 'backup-' . date('Y-m-d-H-i-s') . '.sql';
$backupSql = file_get_contents($backupFile);
// 分割SQL語句
$statements = [];
$keyword = ';';
$length = strlen($keyword);
$start = 0;
while (($pos = strpos($backupSql, $keyword, $start)) !== false) {
$statements[] = substr($backupSql, $start, $pos - $start);
$start = $pos + $length;
}
$statements[] = substr($backupSql, $start);
// 執行SQL語句
foreach ($statements as $statement) {
if (trim($statement) === '') continue;
// 防止執行錯誤的SQL語句
if (strpos($statement, 'CREATE TABLE') !== false) {
$result = $conn->query($statement);
} else {
$result = $conn->query($statement);
}
if (!$result) {
echo "執行錯誤: " . $statement . "<br>";
}
}
echo "數據庫恢復成功";
$conn->close();
?>
mysqldump
)來提高備份效率。通過以上步驟,你可以在PHP中實現基本的數據庫備份與恢復功能。