How To Automatically Run MySQL Dump in Windows and Linux to Backup MySQL Database

Windows

  1. Create a batch file “sweetcoc_ams_backup.bat” for mysqldump. Copy below code into the batch file:-
    @echo off
    REM set mysqldump path
    SET mysqldump_path="C:\wamp64\bin\mysql\mysql5.7.26\bin\mysqldump.exe"
    REM credentials to connect to MySQL server
    SET mysql_user=root
    SET mysql_password=
    REM backup storage location
    SET backup_folder="C:\wamp64\www\database_backups"
    REM backup file name
    SET backup_name=%backup_folder%\sweetcoc_ams_%DATE:~-4%-%DATE:~7,2%-%DATE:~4,2%.sql
    REM create backup
    "C:\wamp64\bin\mysql\mysql5.7.26\bin\mysqldump.exe" -u %mysql_user%
    sweetcoc_ams > %backup_name%
  2. Create a new Task Scheduler that executes the batch file.

 

Linux

  1. Create a new PHP file and copy below code into it.
    <?php
    
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    
    $database = '*****';
    $user = '*****';
    $pass = '*****';
    $host = '*****';
    //$dir = dirname(__FILE__) . '/dump.sql';
    $dir = dirname(__FILE__);
    
    echo "Backing up database to {$dir}.";
    echo "\n";
    
    exec("mysqldump --user={$user} --password={$pass} --host={$host} --no-tablespaces {$database} | zip > \${HOME}/database_backup/{$database}_`date '+%Y-%m-%d_%H:%M'`.sql.zip", $output);
    
    echo "\n";
    echo "Backup completed.";
    
    ?>
  2. Create a new Cron Job and point to the path where the PHP file is saved.
    /usr/local/bin/php
    /home4/sweetcoc/database_backup/mysqldump.php
  3. The Cron Job will save the database as below:-

 

Restoring a Back-Up Database

  1. Go to “D:\” drive in UBS-SERVER.
  2. Compress “AMS Back-Up” folder to “AMS Back-Up.zip”.
  3. Copy “AMS Back-Up.zip” into “C:\wamp64\www\” folder in HP-6305-W7PRO and extract it.
  4. After extracted, move all folders inside “AMS Back-Up” folder to the root folder of “C:\wamp64\www\”. The folder hierarchy should be as below:-
  5. Go to “Start”, search for “wampserver” and run “Wampserver64”.
  6. Wait and ensure the icon is green in “System Tray” that indicates all services are running.
  7. If not then click on “Wampserver64” icon and select “Restart All Services”.
  8. Click on Windows “System Tray” dropdown -> click “Wamserver64” icon -> click “phpMyAdmin”. “phpMyAdmin” will be opened on the browser.
  9. Enter the “username = root” and leave the password empty. Click “Go”.
  10. Click on “sweetcoc_ams” database -> click “Import”.
  11. Click “Choose file”.
  12. Browse “C:\wamp64\www\database_backups”, sort the files by “Date modified” and open the latest SQL file.
  13. Leave everything as it is and click “Go”.
  14. Go to browser and open “http://localhost/punchcard”.
  15. Finally HP-6305-W7PRO” will have the latest version of “E-Punch Card” and “sweetcoc_ams” database.