用PHP备份和恢复MySQL数据库

时间:2014-03-06 07:01:16

标签: php mysql

我正在尝试使用PHP来备份和恢复MySQL数据库:

备份:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'dbpass';
$dbname = 'test';

$output = "D:/backup/test.sql";
exec("D:/xampp/mysql/bin/mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $output");
echo "Backup complete!";

还原:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'dbpass';
$dbname = 'test';

$output = "D:/restore/test.sql";
exec("D:/xampp/mysql/bin/mysql --opt -h $dbhost -u $dbuser -p $dbpass $dbname < $output");
echo "Restore complete!";

但两者都不起作用。备份完成后,我检查空白的test.sql文件。还原完成后,数据库仍为空白。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:9)

使用Php备份的脚本

<?php
define("BACKUP_PATH", "/home/abdul/");

$server_name   = "localhost";
$username      = "root";
$password      = "root";
$database_name = "world_copy";
$date_string   = date("Ymd");

$cmd = "mysqldump --routines -h {$server_name} -u {$username} -p{$password} {$database_name} > " . BACKUP_PATH . "{$date_string}_{$database_name}.sql";

exec($cmd);
?>

要恢复的脚本

<?php

$restore_file  = "/home/abdul/20140306_world_copy.sql";
$server_name   = "localhost";
$username      = "root";
$password      = "root";
$database_name = "test_world_copy";

$cmd = "mysql -h {$server_name} -u {$username} -p{$password} {$database_name} < $restore_file";
exec($cmd);

?>