Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backup and Restore MySQL database in PHP

Tags:

php

mysql

I am trying to use PHP to backup and restore a MySQL database:

Backup:

$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!";

Restore:

$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!";

But both are not working. When Backup is complete then I check test.sql file that is blank. When the restore is complete, the database is still blank.

How can I fix this?

like image 275
DeLe Avatar asked Dec 16 '22 00:12

DeLe


1 Answers

Script to backup using 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);
?>

Script to restore

<?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);

?>
like image 136
Abdul Manaf Avatar answered Jan 04 '23 05:01

Abdul Manaf