在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中实现基本的数据库备份与恢复功能。