简体   繁体   中英

Restore a mysql database backup?

I'm using this command to backup a MySql database:

public function backup() {
    $backup = $this->location.'/'.$this->database.'_backup_'.date('Y').'_'.date('m').'_'.date('d').'.sql';
    $cmd = "c:/xampp/mysql/bin/mysqldump --opt -h localhost -u root $this->database > $backup";
    try {
        system($cmd);
        $error              = false;
        $message['error']   = false;
        $message['message'] = 'Backup successfuly complete';
        return json_encode($message);
    } catch(PDOException $e) {

        $error              = true;
        $message['error']   = true;
        $message['message'] = $e->getMessage();;
        return json_encode($message);
    } 
}

This above works fine, the database is backed up without any problems. And this is the command to restore the back up:

public function restore($backup) {
    $cmd = "c:/xampp/mysql/bin/mysql -h localhost -u root $this->database > $backup";
    try {
        exec($cmd);
        $error              = false;
        $message['error']   = false;
        $message['message'] = 'Restore successfuly complete';
        return json_encode($message);
    } catch(PDOException $e) {

        $error              = true;
        $message['error']   = true;
        $message['message'] = $e->getMessage();;
        return json_encode($message);
    } 
}

The problem with the above function is that when I execute it, the database is not restored, instead the .sql file, in which the database tables are backed up, it's emptied. What is happening ?

Switch the greater than sign to a less than. Right now in your restore job you have the database writing again to a file; now that it's been emptied, it's clearing the file.

mysql -h localhost -u root $this->database < $backup.sql
                                           ^

Generally, > means write, < means read.

您必须更改将< >替换为<的还原命令行:

$cmd = "c:/xampp/mysql/bin/mysql -h localhost -u root $this->database < $backup";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM